Retrieve filename from file descriptor in C

前端 未结 7 1514
野性不改
野性不改 2020-11-22 12:48

Is it possible to get the filename of a file descriptor (Linux) in C?

相关标签:
7条回答
  • 2020-11-22 13:49

    I had this problem on Mac OS X. We don't have a /proc virtual file system, so the accepted solution cannot work.

    We do, instead, have a F_GETPATH command for fcntl:

     F_GETPATH          Get the path of the file descriptor Fildes.  The argu-
                        ment must be a buffer of size MAXPATHLEN or greater.
    

    So to get the file associated to a file descriptor, you can use this snippet:

    #include <sys/syslimits.h>
    #include <fcntl.h>
    
    char filePath[PATH_MAX];
    if (fcntl(fd, F_GETPATH, filePath) != -1)
    {
        // do something with the file path
    }
    

    Since I never remember where MAXPATHLEN is defined, I thought PATH_MAX from syslimits would be fine.

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