C++ File Handling

File handling is an important aspect of programming, as it allows a program to read from or write to a file on a computer’s hard drive. In C++, file handling is performed using a combination of the standard C library functions and C++ stream classes. In this article, we will take a deep dive into file handling in C++, including how to read and write to files, file modes, and file pointers.

fstream class

The fstream class is used for both reading and writing to a file. It is a combination of the ifstream and ofstream classes, which are used for reading and writing respectively. To use this class, you need to include the fstream header file.

#include <fstream>

To open a file, you need to create an object of the fstream class and use the open() function. The open() function takes the name of the file as an argument and opens it for reading and writing.

fstream file;
file.open("example.txt", ios::in | ios::out);

The ios::in flag is used to open the file for reading, and ios::out is used to open the file for writing. If the file does not exist, it will be created. If the file already exists, its contents will be truncated.

Once the file is open, you can read from it using the >> operator and write to it using the << operator.

string line;
file >> line;
cout << "Read from file: " << line << endl;
file << "Writing to file" << endl;

When you’re done with the file, you should close it using the close() function.

file.close();

File Modes

In C++, there are several file modes that can be used to open a file. These modes determine how the file can be accessed and what happens if the file already exists. The most common file modes are:

  • ios::in – open the file for reading
  • ios::out – open the file for writing
  • ios::app – open the file in append mode, new data is added to the end of the file
  • ios::trunc – truncate the file if it already exists

You can combine multiple file modes using the bitwise OR operator (|). For example, to open a file for reading and writing, you would use the following code:

fstream file;
file.open("example.txt", ios::in | ios::out);

It’s also worth mentioning that you can use the ios::ate flag to open a file and move the file pointer to the end of the file. This can be useful if you want to append data to the file without truncating it. The following code snippet demonstrates how to open a file in append mode:

fstream file;
file.open("example.txt", ios::out | ios::app);

It’s important to note that when you open a file in append mode, the file pointer is moved to the end of the file, so you won’t be able to read from the file using the >> operator unless you reposition the pointer using the seekg() function.

File Pointers

File pointers are used to navigate through a file. In C++, file pointers are represented by the streampos class, which is a type of iterator that can be used to move the file pointer to different positions within a file. The streampos class has several member functions that can be used to move the file pointer, such as seekg() and seekp().

The seekg() function can be used to move the input file pointer to a specific position in the file. The function takes two arguments: the first argument is the position to move the pointer to, and the second argument is the starting point for the position. The following code snippet demonstrates how to move the input file pointer to the beginning of a file:

fstream file;
file.open("example.txt", ios::in);
file.seekg(0, ios::beg);

The seekp() function is used to move the output file pointer to a specific position in the file. The function works the same way as seekg(), but it applies to the output file pointer. The following code snippet demonstrates how to move the output file pointer to the end of a file:

fstream file;
file.open("example.txt", ios::out);
file.seekp(0, ios::end);

It’s also worth noting that the tellg() and tellp() functions can be used to get the current position of the input and output file pointers, respectively.

Coding Examples

Reading a File

The following code snippet demonstrates how to open a file, read its contents, and print them to the console:

#include <iostream>
#include <fstream> 
using namespace std;
int main() {
fstream file;
file.open("example.txt", ios::in);
if(file.is_open()) {
string line;
while(getline(file, line)) {
cout << line << endl;
}
file.close();
} else {
cout << "Unable to open file" << endl;
}
return 0;
}

In this code snippet, the fstream object is used to open a file called “example.txt” in input mode. The is_open() function is used to check if the file was successfully opened. If the file was successfully opened, the while loop reads each line of the file using the getline() function and prints it to the console using the cout statement. Once the loop is finished, the file.close() function is called to close the file. If the file is unable to be opened, an error message is printed to the console.

Writing to a File

The following code snippet demonstrates how to open a file, write data to it, and then close the file:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream file;
file.open("example.txt", ios::out);
if(file.is_open()) {
file << "Hello, World!" << endl;
file.close();
} else {
cout << "Unable to open file" << endl;
}
return 0;
}

In this code snippet, the fstream object is used to open a file called “example.txt” in output mode. The is_open() function is used to check if the file was successfully opened. If the file was successfully opened, the file object is used to write the string “Hello, World!” to the file, followed by a newline character. Once the data has been written, the file.close() function is called to close the file. If the file is unable to be opened, an error message is printed to the console.

Appending to a File

The following code snippet demonstrates how to open a file in append mode, write data to it, and then close the file:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream file;
file.open("example.txt", ios::out | ios::app);
if(file.is_open()) {
file << "Hello, World!" << endl;
file.close();
} else {
cout << "Unable to open file" << endl;
}
return 0;
}

In this code snippet, the fstream object is used to open a file called “example.txt” in append mode. The is_open() function is used to check if the file was successfully opened. If the file was successfully opened, the file object is used to write the string “Hello, World!” to the file, followed by a newline character. The data is appended to the file without truncating its contents. Once the data has been written, the file.close() function is called to close the file. If the file is unable to be opened, an error message is printed to the console. It is worth noting that if the file does not exist, it will be created in append mode.

In conclusion, the C++ Standard Template Library provides the fstream class for working with files. The fstream class allows you to open a file in input mode, output mode, or append mode. The is_open() function can be used to check if a file was successfully opened. The getline() function can be used to read a line from a file, and the file object can be used to write data to a file. The close() function should be called when you are finished working with a file to close it. The examples provided demonstrate how to use the fstream class to read from a file, write to a file, and append to a file.

Leave a Reply

Your email address will not be published. Required fields are marked *