from file object to file name

c, c++, file

Solution

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.

Problem

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!

Original source