My use case is to create a function which takes a fileName , an ifsttream/ofstream object and then opens the file for reading/writing accordingly in the given filestream object. also to check whether the operation was successful or not and if successful, returns the filestream object.
My implementation is as following and is based on the assumption that both ifstream and ofstream are derived from fstream.
#include <iostream>
#include <fstream>
using namespace std;
void populate_filehandles(const string &inFileName, fstream &filehandle) {
filehandle.open(inFileName);
if (!filehandle.is_open()) {
cout << "input file : " << inFileName << " could not be opened" << endl;
exit(0);
}
}
int main () {
ifstream inFile;
string inFileName = "abc.txt";
populate_filehandles(inFileName, inFile);
}
the code gives an error that ifstream can not be converted to fstream. is there any other way to solve the problem?
So, as others have suggested, this is due to the fact that
std::ifstreamdoesn't inherit fromstd::fstream. Rather, it inherits fromstd::istresminstead.std::fstreamon the other hand inherits fromstd::iostream. So you can't really do that.Some options you have to work around:
This, however will require you to implement the same function twice. Not necessarily the best idea, but would work.
Something interesting about
std::fstreamis that it has the ability to open a file for reading or writing (or even both I think). So, in theory, you could add a flag to say which direction you want to open it: