是否有一种方式来获得从`FILE *`文件名? [英] Is there a way to get the filename from a `FILE*`?

查看:110
本文介绍了是否有一种方式来获得从`FILE *`文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  获取文件名从文件描述符使用C

有一个简单的和(合理的),便携从获取文件名的方式FILE *

Is there a simple and (reasonably) portable way of getting the filename from a FILE*?

我打开使用 F =的fopen(文件名,...),然后向下传递文件˚F来各种其它功能,其中的一些可能会报告错误。我要报告错误消息的文件名,但避免通过周围的额外的参数。

I open a file using f = fopen(filename, ...) and then pass down f to 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.

我可以创建自定义包装结构{FILE *楼为const char *名称} ,但有可能是一个更简单的方法? (如果 FILE * 不是用开的fopen 我不关心结果。)

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 fopen I don't care about the result.)

推荐答案

在某些平台上(如Linux),您可以通过阅读的/ proc /自/ FD的链接,以获取它/<&号GT; ,像这样:

On some platforms (such as Linux), you may be able to fetch it by reading the link of /proc/self/fd/<number>, as so:

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

This will, on my system, print out /etc/passwd, as desired.

这篇关于是否有一种方式来获得从`FILE *`文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆