Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

fstream

I need to know if there exists a method in ifstream so I can get the name of the file tied to it.

For instance

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

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

like image 952
vlad4378 Avatar asked Jun 28 '15 13:06

vlad4378


2 Answers

As mentioned there's no such method provided by std::fstream and it's derivates. Also std::basic_filebuf doesn't provide such feature.

For simplification I'm using std::fstream instead of std::ifstream/std::ofstream in the following code samples


I would recommend, to manage the underlying file name in a little helper class yourself:

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 can't use another class to pass to some_function() as mentioned above -, may be to use an associative map of fstream* pointers 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()));
}
like image 95
6 revs, 2 users 89% Avatar answered Oct 01 '22 07:10

6 revs, 2 users 89%


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

like image 27
David Haim Avatar answered Oct 01 '22 07:10

David Haim