Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

linux - C print file path from FILE*

FILE * fd = fopen ("/tmp/12345","wb");

If I have the variable fd , how can I print the file path ? (/tmp/12345) in Linux env.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't. Not with just standard C.

On Linux you can do:

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


int print_filename(FILE *f)
{
    char buf[PATH_MAX];
    char fnmbuf[sizeof "/prof/self/fd/0123456789"];
    sprintf(fnmbuf,"/proc/self/fd/%d", fileno(f));
    ssize_t nr;
    if(0>(nr=readlink(fnmbuf, buf, sizeof(buf)))) return -1;
    else buf[nr]='';
    return puts(buf);
}

int main(void)
{
    FILE * f = fopen ("/tmp/12345","wb");
    if (0==f) return EXIT_FAILURE;
    print_filename(f);

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...