Skip to main content

Reading from Files

C++ is a powerful language with a wide array of capabilities, one of which is file handling. In this tutorial, we'll delve into 'Reading from Files' in C++. By the end of this article, you should be able to open a text file in C++, read its contents, and handle potential errors that might occur during this process.

Opening a File

In C++, before you can read from a file, you need to open it. This is done using the fstream library, which enables us to work with files.

#include <fstream>

To open a file, we use the ifstream object from the fstream library. ifstream stands for input file stream. Here's a simple way to open a file:

std::ifstream file("example.txt");

In this line of code, file is the name of the ifstream object we are creating. "example.txt" is the name of the file we want to open.

Reading from a File

Once the file is open, we can start reading from it. We can read from a file in much the same way we read from the console using cin. For example:

std::string line;
while (std::getline(file, line)) {
std::cout << line << '\n';
}

In this piece of code, we're reading the file line by line and printing each line to the console. getline() is a function that reads a line from the file and stores it in the line string. We continue reading lines from the file until there are none left.

Error Handling

Sometimes, things don't go as planned. What if the file you're trying to open doesn't exist? Or what if it can't be read for some reason? To handle such situations, you can use the is_open() function. This function returns true if the file is open and false if it's not. Here's an example:

std::ifstream file("example.txt");

if (file.is_open()) {
std::string line;
while (std::getline(file, line)) {
std::cout << line << '\n';
}
} else {
std::cout << "Unable to open file";
}

In this code, we only try to read the file if it's open. If the file can't be opened, we print an error message instead.

Closing a File

After you're done with a file, it's good practice to close it. You can do this with the close() function:

file.close();

This function closes the file associated with the file stream. It's good practice to always close files after you're done with them to free up resources.

That's it! You now know how to open a text file in C++, read its contents, handle errors, and close the file when you're done. Practice these steps with various text files to cement your understanding. Happy coding!