Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

from file object to file name

Tags:

c++

c

file

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!

like image 776
Tim Avatar asked Dec 02 '22 06:12

Tim


2 Answers

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.

like image 98
Brian Campbell Avatar answered Dec 04 '22 04:12

Brian Campbell


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).

like image 45
Kyle Lutz Avatar answered Dec 04 '22 06:12

Kyle Lutz