Files are used to save or retrieve data from storage devices, e.g. we can store certain information in a text file and later on, can use that information.
Input/output in C++:-
C++ provides <iostream> header file, containing cin and cout which are used to take input and to write output to console window.
However, sometime we want to take input or write output to a certain file instead of console window. For this purpose C++ provides the necessary file handling operation, which we are going to explore in this tutorial.
Necessary Header files:-
For file handling C++ provides the following header files:
- ifstream – It represents Input file stream and enables to read information from files.
- ofstream – It represents Output file stream and enables to write information to files.
- fstream – It represents file stream in general and has both the functionality of ifstream and ofstream i.e. it enable to write as well as read to/from files.
File Handling in C++:-
To start file handling in C++, first of all we have to create a file. One easy way to read/write from file is to create a file in the code directory. In this way we don’t have to worry about the path of file.
Let’s say we create a file “file.txt” in the code directory and want to write the following content to file using ofstream class.
“This is the first line of file.
In this tutorial we are going to learn about file handling in C++.”
Opening a file in C++:-
Apart from programming, when we want to read or write a file, the first step we do is open that file. Same is the case with C++, to perform read/write operation on file, it must be open() first. So, the open function associate the object of fstream with a real file, stored somewhere in memory.
To open a file, we use open() function, which is a member function of ifstream, ofstream and fstream class:
Open( filepath, mode);
Open function takes two arguments:
- The first argument identifies the name and location of file. As we are placing our text file in the code directory. So we just have to mention the name of the file.
- The second argument is optional and it specifies the mode in which we want to open the file.
If no second argument is specified, following are the default values of modes with respect to following classes:
Class | Default mode |
ifstream | ios::in |
ofstream | ios::out |
fstream | ios::in | ios::out |
The following modes can be associated with file handling:
Mode Flags | Description |
ios::in | Open a file for reading. |
ios::out | Open a file for writing. |
ios::binary | Open a file in binary instead of text. |
ios::ate | File pointer points at the end of file after opening. |
ios::app | Appends the new content at the end of file |
ios::trunc | If files exists, all of its content is discarded. |
All of these flags can be combined according to a given scenario by using OR operator (|). Let’s say we want to perform both input and output operations on a file and we want to start from scratch while doing so i.e. delete all of the previous content of file. Then we must combine in, out and trunc flags.
fstream file;
file.open(“myfile.txt”, ios::in | ios::out | ios::trunc);
File opening using constructors:-
As mentioned earlier, the first task we do after declaring class object is to open the file. So there must be a constructor that should do the functionality of open () function and that’s right, C++ provides such a constructor! So the above two lines of code can be combined in one.
fstream file(“myfile.txt”, ios::in | ios::out | ios::trunc);
Check if File opened Successfully?
After opening the file, we got access to the file according to the mode flag. But sometime file stream remain unsuccessful in opening the file due to some reasons, for example file stream tries to access the file which doesn’t exist or file is unable to access because of administrative rights. In this case, C++ provides is_open(), member function of fstream, ifstream and ofstream. Is_open() return true if file stream successfully opened the file otherwise it return false.
So it’s a good practice of error handling to check whether file stream got access to the file or not, before performing required operations on file.
#include "stdafx.h" #include <fstream> #include <iostream> #include <string> using namespace std; int main() { string line; ifstream file("myfile.txt"); if (file.is_open()) { getline(file, line); } else { cout<<"File opening is unsuccessful"; } return 0; }
Closing a file in C++:-
After completing the required operations on file, file must be closed so that if any other program wants to access the file, it won’t create a problem and must be available. For this purpose close() function is implemented in C++. Close() flushes the values in the stream buffer, saves the current content and closes it. It can be called as follow:
file.close();
However, close member function is automatically called by the destructor, once the object of associated file get destroyed.
State flags associated with file streams:-
The following Boolean function exists to check the current states of objects associated with file streaming.
- eof() – The eof() function returns true if the current file which is opened for read or write has reached its end otherwise it would return false.
- bad() – This member function would return true, if any read or write attempt in a file becomes unsuccessful. Otherwise if the specified action become successful, it returns false.
- fail()- This member function is quite similar to bad(), but it also checks verifies if some format error occurs or not? For example we are reading from a file, with the expectation of an integer but an alphabetic character got extracted.
- good() – This member function takes care of all of the above functions, i.e. if either of these above function got set, then it would return false. So by using good(), we could know if failbit or badbit or eofbit is set.
Easy Examples of file handling in C++:-
In this tutorial, we would learn how to write in text files and how to read from text files.
First, we would add few lines to the code.
Then, we would learn how to read those lines in our code.
Writing text to files in C++:-
After successfully opening the file, let’s say we want to add text to the file. We create a text file with the name of myfile.txt and place it the code directory.
We want to add the following text to the file:
The following code would write the required text to the text file in myfile.txt.
#include "stdafx.h" #include <fstream> #include <iostream> #include <string> using namespace std; int main() { ofstream file("myfile.txt"); if (file.is_open()) { file << "This is the tutorial on file handling in C++.\n"; file << "In this tutorial, we would learn how to write in text files and how to read from text files.\n"; file << "First, we would add few lines to the code.\n"; file << "Then, we would learn how to read those lines in our code.\n"; } else { cout<<"File opening is unsuccessful"; } file.close(); return 0; }
As you just notice, writing text to files is quite similar to writing text on console window. Instead of using cout, we use the ofstream class object (in this case, file).
Reading text from files in C++:-
As we have successfully wrote the text in the text file. Let’s read the text we had written in our file.
This time we would have to use ifstream class.
There are two commonly used member function of ifstream class, to read from files.
- Get()
Get member function is used to read from the file character by character until the End Of File (EOF).
- Getline()
Getline() is another member function to read from file. The difference is getine() read the whole line, until the End Of File(EOF).
Example of File reading using get() in C++:-
#include "stdafx.h" #include <fstream> #include <iostream> #include <string>> using namespace std; int main() { char file_char; ifstream file("myfile.txt"); if (file.is_open()) { while (file.get(file_char)) { cout << file_char; } } else { cout<<"File opening is unsuccessful"; } file.close(); return 0; }
Example of File reading using getline() in C++:-
#include "stdafx.h" #include <fstream> #include <iostream> #include <string> using namespace std; int main() { string file_str; ifstream file("myfile.txt"); if (file.is_open()) { while (file.good()) { getline(file, file_str); cout<<file_str<<'\n'; } } else { cout << "File opening is unsuccessful"; } file.close(); return 0; }