Click to See Complete Forum and Search --> : how to get filename from a FILE*


shinto
September 20th, 2001, 10:26 AM
Hi
how to get the name of a file from its pointer

Thank you

AlanGRutter
September 21st, 2001, 09:12 AM
As far as I'm aware, there is no way to obtain the name of the file associated with a FILE *. The only definition I can find for FILE is
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf FILE;




I do not know if you can access these members and I can't see something for filename (only temporary filename).

Alan.

shinto
September 28th, 2001, 05:03 AM
Thank you for your reply.

I am using Digital(comapaq) Unix .

It doesn't even show a member element,

char *_tmpfname in struct FILE.

thanks
Shinto

Paul McKenzie
September 29th, 2001, 09:05 AM
The FILE structure is compiler dependent, so don't expect to find the _tmpfname in your structure.

Sorry, there is no portable way to do this. Even if there was a member in your compiler's version of FILE*, you don't know if the next version of the compiler will get rid of this member.

Instead of just FILE*, why not wrap the FILE structure in another structure that has the filename as a member?

#include <stdio.h>
struct MyFile
{
FILE *fPointer;
char name[255];
// If you use C++
operator FILE *() { return fPointer; }
void fopen(const char *Name, const char *type)
{
fPointer = fopen(Name, type);
if ( fPointer )
strcpy(name, Name);
}
};
//
MyFile MF;
MF.fopen("Test", "r");
// MF.name has the name of the file
// You can close the file using fclose
fclose(MyFile);



Now you use MyFile instead of FILE*. You can pass a MyFile to a function that expects a FILE*, since there is a conversion operator provided (assuming you are using C++).

Regards,

Paul McKenzie