Below you can open the file with an open stream, you can open several files, and it is simply written to the file sequentially. I think the code below can still be optimized with time synchronization and popping unused files to support cache
Any suggestion is welcome.
class OpenFile { string fileName; static map<string, unique_ptr<mutex>> fmap; bool flag; public : OpenFile(string file) : fileName(file) { try { if(checkFile(file)) { flag = false; fmap.emplace(file, make_unique<mutex>()); } else { flag = true; } } catch(string str) { cout << str << endl; } } void writeToFile(const string& str) const { if (flag) { lock_guard<mutex> lck(*fmap.find(fileName)->second); ofstream ofile(fileName, ios::app); ofile << "Writing to the file " << str << endl; ofile.close(); } else { ofstream ofile(fileName, ios::app); ofile << "Writing to the file " << str << endl; ofile.close(); } } string ReadFile() const { string line; if (flag) { lock_guard<mutex> lck(*fmap.find(fileName)->second); ifstream ifile(fileName, ios::in); getline(ifile, line); ifile.close(); } else { ifstream ifile(fileName, ios::in); getline(ifile, line); ifile.close(); } return line; } OpenFile() = delete; OpenFile& operator=(const OpenFile& o) = delete; static bool checkFile(string& fname); }; bool OpenFile::checkFile(string& fname) { if (fmap.find(fname)==fmap.end()) { return true; } else return false; }
source share