basic_ifstream::open

Open is used to open a file or reopen a file after closing it.

void open(const char* s, ios::openmode mode = ios::in);

Remarks

The default open mode is ios::in, but can be one of several modes. (see below) A stream is opened and prepared for input or output as selected.

There is no return.

If an attempt is made to open a file in an inappropriate file opening mode, the file will not open and a test for the object will not give false, therefore use the function is_open() to check for file openings.

Table 1. Legal basic_ifstream file opening modes
Opening Modes stdio equivalent
Input Only  
ios:: in "r"
ios:: binary | ios::in "rb"
Input and Output  
ios::in | ios::out "r+"
ios::binary | ios::in | ios::out "r+b"
ios:: in | ios::out | ios::trunc "w+"
ios::binary | ios::in | ios::out | ios::trunc "w+b"
ios::binary | ios:: out | ios::app "ab"
Listing: Example of basic_ifstream::open() usage:
// The ewl-test file contains:
// CodeWarrior "Software at Work"

#include <iostream>
#include <fstream>
#include <cstdlib>

char inFile[] = "ewl-test";

int main()
{
using namespace std;
   ifstream in;
   in.open(inFile);          

   if(!in.is_open())
      {cout << "can't open input file"; exit(1);}

   char c = NULL;
   while((c = in.get()) != EOF)
   {
      cout << c;   
   }
   in.close();
   return 0;
}

Result:

  CodeWarrior "Software at Work"