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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With