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?
void
. Now the only prolbem to solve is the error message, at the moment is say "input file" which isn't necessarily true. – johnifstream
andofstream
are derived fromfstream
. Surprises are usually caused by one or more assumptions being mistaken. – molbdniloifstream
inherits fromistream
,ofstream
inherits fromostream
,fstream
inherits fromiostream
. So the code as currently written cannot work. Reference – john