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?