Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C print file path from FILE*

FILE * fd = fopen ("/tmp/12345","wb");

If I have the variable fd , how can I print the file path ? (/tmp/12345) in Linux env.

like image 436
joif doi Avatar asked Sep 24 '19 13:09

joif doi


2 Answers

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);

}
like image 164
PSkocik Avatar answered Sep 16 '22 16:09

PSkocik


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.

like image 32
John Bode Avatar answered Sep 19 '22 16:09

John Bode