File open mode - C++ File Stream

C++ examples for File Stream:File Operation

Introduction

When using the fstream class's open() function, two arguments are required:

  • a file name and
  • a mode indicator.

Here are the permissible mode indicators:

IndicatorDescription
ios::in Open a text file in input mode
ios::outOpen a text file in output mode
ios::appOpen 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::nocreateIf file doesn't exist, open fails
ios::noreplace If file exists, open for output fails

Demo Code

#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;
}

Result


Related Tutorials