Skip to main content

12.2) Opening Files


In versions of the C++ standard prior to C++11, opening a file is simplest if the filename is represented as a C-style string (a null-terminated char array):

char filename[40];
...
ifstream infile(filename);
if (not infile.is_open()) {
  // deal with failure to open file
}

If your filename is a string object instead, you must call its c_str method in order to obtain the required C-style string:

string filename;
...
ifstream infile(filename.c_str());
if (not infile.is_open()) {
  // Deal with failure to open file
}

If your compiler supports C++11 then you can use string objects directly as filenames, without having to call the c_str method.

Note in these examples how the is_open method is called on the file stream object after attempting to open the file. This method will return true if opening the file succeeded, false if it failed. Note also that there is nothing significant about the use of infile as the name of the stream variable in these examples; you can use something else if you prefer.