Getting filename (or path) from fstream

C++File IoFstream

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

you may also design a little class which inherits from fstream and behaves like a fstream but also stores its file name.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPavel OganesyanView Question on Stackoverflow
Solution 1 - C++NawazView Answer on Stackoverflow
Solution 2 - C++WalterView Answer on Stackoverflow