可能重复:
从C中的文件描述符获取文件名
是否有一种简单且(合理)可移植的方式从文件中获取文件名FILE*
?
我使用打开文件f = fopen(filename, ...)
,然后传递f
给其他各种函数,其中一些可能会报告错误.我想在错误消息中报告文件名,但避免传递额外的参数.
我可以创建一个自定义包装器struct { FILE *f, const char *name }
,但是可能有更简单的方法吗?(如果FILE*
未打开使用fopen
我不关心结果.)
dav*_*idg 12
在某些平台(例如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);
}
Run Code Online (Sandbox Code Playgroud)
这将在我的系统上/etc/passwd
根据需要打印出来.