c - 有没有办法从 `FILE*` 获取文件名?

标签 c

<分区>

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 , 根据需要。

关于c - 有没有办法从 `FILE*` 获取文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4862327/

相关文章:

c++ - 隔离容易崩溃的 (SEGV) 但将关键的遗留代码加速到单独的二进制文件中

c - 遍历数组以检查条件

c - 免费 GSL 矩阵的正确方法是什么?

C 字符数组在传递给函数后损坏

控制台退出循环,C 中的值不正确

c - 分配给位域时的 GCC 转换警告

c++ - 黑白 char* str[]、char *str 和 char str[] 的区别

使用 SSL 密码连接 nginx websocket

c - 写入 c MPI 中的输出文件

c - 从 : malloc/free/malloc/free 的设计模式中获取与 malloc 相关的错误