C print file path from FILE*

て烟熏妆下的殇ゞ 提交于 2019-12-29 08:51:07

问题


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

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


回答1:


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.




回答2:


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

}



回答3:


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.



来源:https://stackoverflow.com/questions/58081928/c-print-file-path-from-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!