C++ examples for File Stream:File Operation
Creates the info.bak file as a duplicate of the info.txt file
#include <iostream> #include <fstream> #include <cstdlib> #include <string> using namespace std; int main()/*from ww w. j a va2 s .com*/ { string fileOne = "info.txt"; string fileTwo = "info.bak"; char ch; ifstream inFile; ofstream outFile; try { inFile.open(fileOne.c_str()); if (inFile.fail()) throw fileOne; } catch(string in) { cout << in << " was not successfully opened." << endl << " No backup was made." << endl; exit(1); } try { outFile.open(fileTwo.c_str()); if (outFile.fail()) throw fileTwo; while ((ch = inFile.get()) != EOF) outFile.put(ch); inFile.close(); outFile.close(); } catch(string out) { cout << out << " was not successfully opened." << endl; exit(1); } cout << "A backup of " << fileOne << " named " << fileTwo << " was successfully made." << endl; return 0; }