一、代码示例
示例代码首先根据文件名获取文件描述符,然后根据文件描述符获得文件绝对路径(文件名),如果已知文件描述符fd,可直接通过下面两条代码获得文件绝对路径(文件名):
snprintf(buf,sizeof(buf), "/proc/self/fd/%d", abs_fd);
readlink(buf,obj_file,SIZE);
obj_file 就为文件绝对路径,完整代码示例如下:
fd.c:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#define SIZE 128
int main(int argc, char* argv[])
{
int abs_fd;
char *obj_file;
obj_file = malloc(SIZE);
char buf[SIZE] = {'\0'};
if(argc != 2)
{
printf("please input the filename \n");
return 0;
}
if ((abs_fd = open(argv[1], O_RDWR | O_CREAT, 0666)) < 0)
{
perror("open file error\n");
return 0;
}
snprintf(buf,sizeof(buf), "/proc/self/fd/%d", abs_fd);
if (readlink(buf,obj_file,SIZE) < 0)
{
perror("readl