c - Is there a way to get the filename from a `FILE*`? -
possible duplicate: getting filename file descriptor in c
is there simple , (reasonably) portable way of getting filename file*
?
i open file using f = fopen(filename, ...)
, pass downwards f
various other functions, of may study error. i'd study filename in error message avoid having pass around parameter.
i create custom wrapper struct { file *f, const char *name }
, there perhaps simpler way? (if file*
wasn't opened using fopen
don't care result.)
on platforms (such linux), may able fetch reading link of /proc/self/fd/<number>
, so:
#include <stdio.h> #include <unistd.h> #include <string.h> int main(void) { char path[1024]; char result[1024]; /* open file, file descriptor. */ file *f = fopen("/etc/passwd", "r"); int fd = fileno(f); /* read out link our file descriptor. */ sprintf(path, "/proc/self/fd/%d", fd); memset(result, 0, sizeof(result)); readlink(path, result, sizeof(result)-1); /* print result. */ printf("%s\n", result); }
this will, on system, print out /etc/passwd
, desired.
c
No comments:
Post a Comment