Menu
Coddy logo textTech

Opening Files

Lesson 4 of 23 in Coddy's C++ File Handling course.

Before we start learning how to read from or write to files, first you need to learn how to open files in C++. 

Files modes of operation

  • ifstream - mode for inputting from a file
  • ofstream - mode for outputting from a file
  • fstream - mode for doing both

We will use the first two ways, just to separate the files we open for input, with the files that we open for output.

So, to open a file in inputting mode, we first create an object from the ifstream class. And then we open the given file.

ifstream file;
file.open("example.txt")
  • file - name of the object that we create
  • “example.txt” - name of the file that we are opening

The second practical thing to do is to check if we actually opened the file successfully. We do that with an if-statement and using the file.is_open()

Example:

ofstream file;
file.open("example.txt");

if(file.is_open())
	cout << "File succesfully opened!";
else
	cout << "Unable to open file.";
challenge icon

Challenge

Easy

Open the three files, “example.txt”, “document.txt”, “text.txt”. If a file is successfully open print out to standard output File opened successfully, if not print out Unable to open the given file

Try it yourself

#include <iostream>
// Include the needed library

using namespace std;

int main() 
{
    
    // Enter your code here
    
    return 0;
}

All lessons in C++ File Handling