C语言 有没有办法从`FILE*`获取文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4862327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to get the filename from a `FILE*`?
提问by nominolo
Possible Duplicate:
Getting Filename from file descriptor in C
可能的重复:
从 C 中的文件描述符获取文件名
Is there a simple and (reasonably) portable way of getting the filename from a FILE*?
是否有一种简单且(合理)可移植的方式从FILE*.
I open a file using f = fopen(filename, ...)and then pass down fto various other functions, some of which may report an error. I'd like to report the filename in the error message but avoid having to pass around the extra parameter.
我打开一个文件f = fopen(filename, ...),然后传递f给其他各种函数,其中一些可能会报告错误。我想在错误消息中报告文件名,但避免传递额外的参数。
I could create a custom wrapper struct { FILE *f, const char *name }, but is there perhaps a simpler way? (If the FILE*wasn't opened using fopenI don't care about the result.)
我可以创建一个自定义包装器struct { FILE *f, const char *name },但可能有更简单的方法吗?(如果FILE*没有打开使用fopen我不关心结果。)
采纳答案by davidg
On some platforms (such as Linux), you may be able to fetch it by reading the link of /proc/self/fd/<number>, as so:
在某些平台(例如 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);
}
This will, on my system, print out /etc/passwd, as desired.
这将在我的系统上/etc/passwd根据需要打印出来。
回答by Nordic Mainframe
It's a bit difficult, because a FILE* can read/write from a file handle which isn't associated with a named file at all (for example an unnamed pipe or a socket). You canobtain the file handle with fileno() and then there are system specific ways to learn about the file name. Here's a discussion on how to do this under Linux:
这有点困难,因为 FILE* 可以从根本不与命名文件(例如未命名管道或套接字)关联的文件句柄中读取/写入。您可以使用 fileno() 获取文件句柄,然后有系统特定的方法来了解文件名。以下是有关如何在 Linux 下执行此操作的讨论:
Getting Filename from file descriptor in C
and under Windows this isn't much easier either:
在 Windows 下,这也不是那么容易:
http://msdn.microsoft.com/en-us/library/aa366789(VS.85).aspx(as an extra step here, you use _get_osfhandle() to get the Windows file handle from the c-library file descriptor)
http://msdn.microsoft.com/en-us/library/aa366789(VS.85) .aspx(作为这里的额外步骤,您使用 _get_osfhandle() 从 c-library 文件描述符获取 Windows 文件句柄)

