C print file path from FILE*

前端 未结 3 1713
生来不讨喜
生来不讨喜 2020-12-11 05:44
FILE * fd = fopen (\"/tmp/12345\",\"wb\");

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

相关标签:
3条回答
  • 2020-12-11 06:07

    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);
    
    }
    
    0 讨论(0)
  • 2020-12-11 06:16

    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.

    0 讨论(0)
  • 2020-12-11 06:17

    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.

    0 讨论(0)
提交回复
热议问题