C print file path from FILE*

前端 未结 3 1721
生来不讨喜
生来不讨喜 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: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 
    #include 
    
    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.

提交回复
热议问题