Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

c++ - Getting filename (or path) from fstream

Can I get a file name or its path from a fstream object? I looked through the methods of fstream and didn't find anything close to it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, that is not possible, not at least in the Standard conformant implementation of the library.

The fstream class doesn't store the filename, and doesn't provide any function for retrieving it.

So one way to keep track of this information is to use std::map as:

std::map<std::fstream*, std::string> stream_file_table;

void f()
{
  //when you open a file, do this:
  std::fstream file("somefile.txt");

  stream_file_table[&file] = "somefile.txt"; //store the filename

  //..
  g(file);
}
void g(std::fstream & file)
{
    std::string filename = stream_file_table[&file]; //get the filename
    //...
}

Or, simply pass around the filename as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...