Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a file's name from FILE* struct in C

Tags:

c

file

Is it possible to retrieve a file's name in C? If a file is created like the following:

     FILE *f = fopen ("foo.txt", "r");

And the "foo.txt" comes from a variable out of scope. Is there a way to retrieve it from the FILE struct?

like image 611
rahmu Avatar asked Nov 02 '11 23:11

rahmu


1 Answers

You can't in fact retrieve the file names from your FILE objects.

However, if the name being passed to fopen is important to you, and that variable is out of scope for whatever reason, you could always wrap a FILE* in a struct, ie.

struct file_with_name {
   FILE *f;
   char *name; /* OR char name[MAX] */
}

At least that's what I'd do but it depends on what you're actually trying to do.

like image 137
AusCBloke Avatar answered Oct 08 '22 07:10

AusCBloke