在给定FILE指针的情况下,如何找到文件名?

可能重复:
从C中的文件描述符获取文件名
从C中的文件指针获取文件名

我在这里有一个function:

handle_file(FILE *file) { if(condition) { print filename and other msg; } } 

我们在这里唯一知道的是指向文件的指针; 是否可以根据指针获取文件名?

查看此答案以获取文件描述符和此答案以从文件描述符中获取文件名。 在Linux上应该没问题(不确定其他操作系统)。

这是一个快速工作的例子(在Cygwin / Win7下测试):

 #include  #include  #include  int main() { int MAXSIZE = 0xFFF; char proclnk[0xFFF]; char filename[0xFFF]; FILE *fp; int fno; ssize_t r; // test.txt created earlier fp = fopen("test.txt", "r"); if (fp != NULL) { fno = fileno(fp); sprintf(proclnk, "/proc/self/fd/%d", fno); r = readlink(proclnk, filename, MAXSIZE); if (r < 0) { printf("failed to readlink\n"); exit(1); } filename[r] = '\0'; printf("fp -> fno -> filename: %p -> %d -> %s\n", fp, fno, filename); } return 0; } 

输出:

 fp -> fno -> filename: 0x80010294 -> 3 -> /tmp/test.txt 

这可以分两个阶段完成。 首先,您需要获取文件描述符,然后您将需要恢复文件名。 以下是一个例子,但是有一些严重的缓冲区溢出漏洞!

 #include  #include  char * recover_filename(FILE * f) { int fd; char fd_path[255]; char * filename = malloc(255); ssize_t n; fd = fileno(f); sprintf(fd_path, "/proc/self/fd/%d", fd); n = readlink(fd_path, filename, 255); if (n < 0) return NULL; filename[n] = '\0'; return filename; } 

当我搜索时,如果你是root并且命令lsof存在于你的系统中,那么你可以使用fileno(fp)来获取打开文件的lsof -d descriptor 。 你可以尝试一下。

否则,如果要分析文件夹中的所有目录和文件,可以使用opendir和struct dirent。 这不是使用文件指针,但可能对您有用,具体取决于您的代码的工作方式。

 DIR *BaseDIR; struct dirent *curentDir; BaseDIR = opendir("path/to/the/directory"); while((curentDir = readdir(BaseDIR)) != NULL){ printf("directory or file name : %s\n",curentDir->d_name); } closedir(BaseDIR); 

我认为这是可能的。
使用fileno(fp)来获取描述符。
然后,您可以使用fstat()函数。

 The fstat() function shall obtain information about an open file asso‐ ciated with the file descriptor fildes, and shall write it to the area pointed to by buf. 

int fstat(int fildes, struct stat *buf);

那么,你可以在*buf获得大量的文件信息。