user3288944
user3288944

Reputation: 81

C++: Retrieving filename from istream

I have a function:

void read_file(istream &file);

In main(), I would pass in something like:

ifstream file;
file.open(argv[1]);
read_file(file);

Now, inside the read_file function, is there a way to get name of the file passed in? For example, if argv[1] was "data1.txt", can we extract that string from inside read_file?

Thanks in advance.

By the way, I've tried:

cout << file << endl; // Doesn't work.
cout << &file << endl; // Same result.

They print an address.

Upvotes: 0

Views: 1801

Answers (3)

user3344003
user3344003

Reputation: 21627

The kind of thing you are asking for is normally done at the operating system level. That tends not to be portable and does not make it into standard libraries.

For example, supposed you opened the file with

 "~/../something.txt"

What should the library return as the file name?

What if you opened a symbolic link?

What if the operating system permits multiple file names through directories for the same file?

The amount that the operating system can fill in depends upon the system itself. For example, if you've ever worked on a VMS system, it's system services do a lot of filling in that Unix and Dos systems do not.

Library designers avoid these system dependent problems by not including these features.

Upvotes: 0

trevor
trevor

Reputation: 2300

You could store the file name in a class level variable within main() so that it would be available for output within your read_file function:

const char* inFile = "";       // input file

int main(int argc, char* argv[])
{
    // assign value from args to
    // class level variable 'inFile'
    inFile = argv[1];       
}

Then you could output 'inFile' within your read_file function:

cout << inFile << endl;

Upvotes: 0

David G
David G

Reputation: 96810

File streams don't provide any way of retrieving the file name (or the open mode for that matter). What you can do is store it in the stream's cache using pword() and xalloc(). You would also need to register the necessary callbacks to resolve lifetime dependencies.

Upvotes: 4

Related Questions