在给定FILE指针的情况下,如何查找文件名? [英] How do I find a filename, given a FILE pointer?

查看:166
本文介绍了在给定FILE指针的情况下,如何查找文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
从C中的文件描述符获取文件名
从C中的文件指针获取文件名

Possible Duplicate:
Getting Filename from file descriptor in C
Obtain filename from file pointer in C

我在这里有一个功能:

handle_file(FILE *file)
{
    if(condition)
    {
        print filename and other msg;
    }
}

我们在这里唯一知道的是指向文件的指针.是否可以根据指针获取文件名?

The only thing we know here is the a pointer to the file; is it possible to get the filename according to the pointer?

推荐答案

查看此答案以获得文件描述符和此答案以从文件描述符中获取文件名.在Linux上应该可以(不确定其他操作系统).

Check out this answer to obtain file descriptor and this answer to get file name from file descriptor. Should be OK on Linux (not sure about other operating systems).

这是一个快速工作的示例(在Cygwin/Win7下测试):

Here's a quick working example (tested under Cygwin/Win7):

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
    int MAXSIZE = 0xFFF;
    char proclnk[0xFFF];
    char filename[0xFFF];
    FILE *fp;
    int fno;
    ssize_t r;

    // test.txt created earlier
    fp = fopen("test.txt", "r");
    if (fp != NULL)
    {
        fno = fileno(fp);
        sprintf(proclnk, "/proc/self/fd/%d", fno);
        r = readlink(proclnk, filename, MAXSIZE);
        if (r < 0)
        {
            printf("failed to readlink\n");
            exit(1);
        }
        filename[r] = '\0';
        printf("fp -> fno -> filename: %p -> %d -> %s\n",
                fp, fno, filename);
    }
    return 0;
}

输出:

fp -> fno -> filename: 0x80010294 -> 3 -> /tmp/test.txt

这篇关于在给定FILE指针的情况下,如何查找文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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