简体   繁体   中英

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.

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.

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM