Possible Duplicate:
Getting Filename from file descriptor in C
是否有一种简单且(合理)可移植的方法从 FILE*
获取文件名?
我使用 f = fopen(filename, ...)
打开一个文件,然后将 f
传递给各种其他函数,其中一些可能会报告错误。我想在错误消息中报告文件名,但避免传递额外参数。
我可以创建一个自定义包装器 struct { FILE *f, const char *name }
,但是否有更简单的方法? (如果 FILE*
不是使用 fopen
打开的,我不关心结果。)
在某些平台(例如 Linux)上,您可以通过阅读 /proc/self/fd/<number>
的链接来获取它。 ,因此:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(void)
{
char path[1024];
char result[1024];
/* Open a file, get the file descriptor. */
FILE *f = fopen("/etc/passwd", "r");
int fd = fileno(f);
/* Read out the link to our file descriptor. */
sprintf(path, "/proc/self/fd/%d", fd);
memset(result, 0, sizeof(result));
readlink(path, result, sizeof(result)-1);
/* Print the result. */
printf("%s\n", result);
}
这将在我的系统上打印出 /etc/passwd
, 根据需要。