开发者

from file object to file name

I wonder if we can get the file name including its path from the file ob开发者_高级运维ject 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!


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜