Skip to content

Instantly share code, notes, and snippets.

@edgesider
Created May 10, 2019 15:24
Show Gist options
  • Save edgesider/11aba0b03f8beeedea7a475bd5c0af54 to your computer and use it in GitHub Desktop.
Save edgesider/11aba0b03f8beeedea7a475bd5c0af54 to your computer and use it in GitHub Desktop.
Linux从文件描述符获取文件名

通过fchdir和getcwd获取文件描述符对应的文件名

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
    char cwdbuf[4096];
    int fd;

    fd = open("/home/kai/test_lang/", O_RDONLY);
    if (fd == 0) {
        perror("open");
        _exit(-1);
    }

    if (fchdir(fd) != 0) {
        perror("fchdir");
        _exit(-1);
    }

    if (getcwd(cwdbuf, sizeof(cwdbuf)) == NULL) {
        perror("getcwd");
        _exit(-1);
    }
    else {
        printf(cwdbuf);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment