C++ Simple File Handling

C++ has two basic stream classes to handle files, ifstream and ofstream. To use them, include the header file fstream. Here is an example:

 1#include <fstream>
 2#include <iostream>
 3using namespace std;
 4
 5int main()
 6{
 7  char str[10];
 8
 9  // Creates an instance of ofstream, and opens example.txt
10  ofstream a_file ("example.txt");
11  // Outputs to example.txt through a_file
12  a_file << "This text will now be inside of example.txt";
13  // Close the file stream explicitly
14  a_file.close();
15  // Opens for reading the file
16  ifstream b_file ("example.txt");
17  // Reads one string from the file
18  b_file >> str;
19  // Should output 'this'
20  cout<< str << "\n";
21  cin.get();    // wait for a keypress
22  // b_file is closed implicitly here
23}

The default mode for opening a file with ofstream’s constructor is to create it if it does not exist or delete everything in it if something does exist. If necessary, we can give a second argument that specifies how the file should be handled. They are listed below:

1ios::app   // Append to the file
2ios::ate   // Set the current position to the end
3ios::trunc // Delete everything in the file

For example:

1ofstream a_file("test.txt", ios::app);

This will open the file without destroying the current contents and allow you to append new data. When opening files, be very careful not to use them if the file could not be opened. This can be tested for very easily:

1ifstream a_file ("example.txt");
2
3if (!a_file.is_open()) {
4  // The file could not be opened
5}
6else {
7  // Safely use the file stream
8}