Can I get the name of the file used in ifstream / ofstream?

I need to know if a method exists in the ifstream, so I can get the name of the associated file.

for example

void some_function(ifstream& fin) {
    // here I need get name of file
}

      

Is there a method in ifstream / ofstream that allows you to get this?

+3


source to share


3 answers


As mentioned, no such method is provided std::fstream

and it is output. Also std::basic_filebuf

does not provide such a feature.

For simplicity, I use std::fstream

instead of std::ifstream

/ std::ofstream

in the following code examples


I would recommend to manage the base filename in a small helper class:



class MyFstream {
public:
    MyFstream(const std::string& filename) 
    : filename_(filename), fs_(filename) {
    }

    std::fstream& fs() { return fs_; }
    const std::string& filename() const { return filename_; }
private:
    std::string filename_;
    std::fstream fs_;
};

void some_function(MyFstream& fin) {
    // here I need get name of file
    std::string filename = fin.filename();
}

int main() {
    MyFstream fs("MyTextFile.txt");
    some_function(fs):
}

      


Another alternative - if you cannot use another class to go to some_function()

, as mentioned above, there might be an associative map of pointers fstream*

and their associated filenames:

class FileMgr {         
public:
     std::unique_ptr<std::fstream> createFstream(const std::string& filename) {
          std::unique_ptr<std::fstream> newStream(new std::fstream(filename));
          fstreamToFilenameMap[newStream.get()] = filename;
          return newStream;
     }
     std::string getFilename(std::fstream* fs) const {
         FstreamToFilenameMap::const_iterator found = 
              fstreamToFilenameMap.find(fs);
         if(found != fstreamToFilenameMap.end()) {
             return (*found).second;
         }
         return "";
     }
private:
     typedef std::map<std::fstream*,std::string> FstreamToFilenameMap;

     FstreamToFilenameMap fstreamToFilenameMap;
};

FileMgr fileMgr; // Global instance or singleton

void some_function(std::fstream& fin) {
     std::string filename = fileMgr.getFilename(&fin);
}

int main() {
    std::unique_ptr<std::fstream> fs = fileMgr.createFstream("MyFile.txt");

    some_function(*(fs.get()));
}

      

+3


source


Not. C ++ streams do not preserve file name or path. but since you need a string to initialize the stream anyway, you can just save it for future use.



+5


source


No, there is no such method.

0


source







All Articles