Reputation: 31577
Is there any way in C++ to identify a file stream? It doesn't really matter what it is, as long as two streams created from the same file have the same "id"; anything that would allow me to say that two streams created from the same file are equivalent (not equal).
Upvotes: 3
Views: 219
Reputation: 93476
The only common identifier that isn't perhaos OS specific would be the file-path or device name itself, but iostream objects do not provide access to that information.
One solution is to sub-class the stream object and provide the functionality you need there. An unsatisfactory eample:
class id_fstream : public std::fstream
{
public :
id_fstream( const char * filename,
ios_base::openmode mode = ios_base::in | ios_base::out ) :
fstream( filename, mode ), m_filename( filename)
{
// do nothing
} ;
const std::string& filename()
{
return m_filename ;
}
private :
std::string m_filename ;
} ;
Then you can write code such as:
if( id_fstreamA.filename() == id_fstreamB.filename() )
{
...
}
It does not work however if one file was opened with a different reletive or absolute path or via an alias. You might solve that problem by obtaining the current working directory via an OS specific call and therby resolving a complete path to any non-absolute path used.
Upvotes: 2
Reputation: 9309
I believe there is no such way.
It is assumed that the programmer has enough ways to keep track of different streams himself or makes a custom struct to put e.g. the file path as a string
inside that struct or something similar. e.g. you could have a struct like this:
struct FileStream {
char* FilePath;
istream FileStream;
}
And then to see if two FileStream
s are on the same file, you could do something like:
myStringCompare(fs1.FilePath, fs2.FilePath);
I hope this helps.
Upvotes: 0
Reputation: 740
As far as I can tell, there's no built-in way to compare two file streams. You would either have to compare the two pointers, which would require you to keep track of streams which are the same (which might not be possible in your case, judging from the format of the question), or read the data in both file streams and compare it instead.
Upvotes: 0