FILE * fd = fopen (\"/tmp/12345\",\"wb\");
If I have the variable fd
, how can I print the file path ? (/tmp/12345) in Linux env.
You can't. Not with just standard C.
On Linux you can do:
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>
int print_filename(FILE *f)
{
char buf[PATH_MAX];
char fnmbuf[sizeof "/prof/self/fd/0123456789"];
sprintf(fnmbuf,"/proc/self/fd/%d", fileno(f));
ssize_t nr;
if(0>(nr=readlink(fnmbuf, buf, sizeof(buf)))) return -1;
else buf[nr]='\0';
return puts(buf);
}
int main(void)
{
FILE * f = fopen ("/tmp/12345","wb");
if (0==f) return EXIT_FAILURE;
print_filename(f);
}
Since MacOS don't have /proc
, fcntl
is a good alternative for fetching a file descriptor's path!
Here's a working example:
#include <sys/syslimits.h>
#include <fcntl.h>
char filePath[PATH_MAX];
if (fcntl(fd, F_GETPATH, filePath) != -1)
{
printf("%s", filePath);
}
But it works only on MacOS, for Linux PSkocik's solution using readlink
seems to be the best answer.
There's no standard way to retrieve a pathname from a FILE *
object, mainly because you can have streams that aren't associated with a named file (stdin
, stdout
, stderr
, pipes, etc.). Individual platforms may supply utilities to retrieve a path from a stream, but you'd have to check the documentation for that platform.
Otherwise, you're expected to keep track of that information manually.