tags:

views:

173

answers:

3

Hi,

I wonder if we can get the file name including its path from the file object that we have created for the file name in C and in C++ respectively

FILE *fp = fopen(filename, mode); // in C
ofstream out(filename); // in C++
ifstream in(filename);  // in C++

Thanks!

+9  A: 

There is no portable way to retrieve the file name of a FILE* object. It may not even be associated with an actual file (e.g. a FILE pointer for stdout).

Kyle Lutz
+7  A: 

You can't, in general. The file may not ever have had a file name, as it may be standard input, output, or error, or a socket. The file may have also been deleted; on Unix at least, you can still read to or write from a file that has been deleted, as the process retains a reference to it so the underlying file itself is not deleted until the reference count goes to zero. There may also be more than one name for a file; you can have multiple hard links to a single file.

If you want to retain the information about where a file came from, I would suggest creating your own struct or class that consists of a filename and the file pointer or stream.

Brian Campbell
+1  A: 

There is no portable way. However particular platforms sometimes have ways to do that.

In Windows, if you can get the file's HANDLE (like the one you get from ::CreateFile() ), you can get the path from that using something like ZwQueryInformationFile().

From a FILE *, you can get a (Unix-style) file id using _fileno(). Then call _get_oshandle() to get the HANDLE.

Not sure how to do that from an std::ofstream, but you can research that.

Not sure how to do that on other OSes but it may be possible.

Michael J