C++ examples for File Stream:File Operation
When using the fstream class's open() function, two arguments are required:
Here are the permissible mode indicators:
Indicator | Description |
---|---|
ios::in | Open a text file in input mode |
ios::out | Open a text file in output mode |
ios::app | Open a text file in append mode |
ios::ate | Go to the end of the opened file |
ios::binary | Open a binary file in input mode (default is text file) |
ios::trunc | Delete file contents if it exists |
ios::nocreate | If file doesn't exist, open fails |
ios::noreplace | If file exists, open for output fails |
#include <iostream> #include <fstream> #include <cstdlib> // needed for exit() #include <string> using namespace std; int main()/* w w w . j a va2s .co m*/ { string filename; ifstream inFile; cout << "Please enter the name of the file you wish to open: "; cin >> filename; inFile.open(filename.c_str(),ios::in); // open the file if (inFile.fail()) // check for successful open { cout << filename << " was not successfully opened\n Please check that the file currently exists." << endl; exit(1); } cout << "\nThe file has been successfully opened for reading.\n"; return 0; }