File Handling in C++
The process of writing/storing output of program to file in secondary storage is know as file handling. Sometime this process also used to read data from files as input. C++ file handling process is done with the help of fstream header file. User must have to include fstream header file before reading/writing data to and from the files.
For file IO operations using C++ the following steps are followed.
- Create file stream object
- Open file using fstream object
- Read/Write Data using fstream object
- Close file
Fstream Open() function:
Open method is part of main fstream class, this method is used to open file by providing its path as an input.
Syntax:
Syntax of obj.open() method is as follow.
obj.open("File Path");
Fstream close() function:
Close() method is used to close the file successfully when reading/writing operations completed.
Syntax:
The syntax of fsream close method is as follow.
obj.close();
CPP File Handling Write Example:
#include <iostream>
#include <fstream>
#include <cstdlib> // for exit function
using namespace std;
int main()
{
ofstream store; // object to save data
int x; // counter variable
// values to store on file
int arr[4] = {12, 33, 7, 10};
store.open("D://testFile.txt"); // opens the file
if( !store ) { // object cannot open the file.
cerr << "File cannot be opened!...." << endl;
exit(1);
}
for (x=0; x<4; x++)
store << arr[x] << endl;
store.close();
return 0;
}
CPP File Handling Read Example:
In this code example we use character type variable and then read file character by character. In every iteration we read character from file and store it in the char type variable and print on the screen using cout output statement. We can also read file line by line using getline function.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream my_file; // file stream object
// opening file in reading mode
my_file.open("D://testFile.txt", ios::in);
// checking either file exist.
if (!my_file) {
cout << "No such file";
}
else {
char ch; // for reading character
while (1) {
my_file >> ch;
if (my_file.eof())
break; // for terminating loop
cout << ch;
}
}
my_file.close(); // closing file.
return 0;
}
CPP File Handling Functions:
The commonly used file handling functions are as follow.
Sr. | Function Identifier | Description/Use |
1 | open() | This method is used to open file using fstream object. This function take two parameter one path to file and othe mode for file operation. |
2 | close() | close() method is used to close file successfully. OS automatically close file after termination of program. But it is good practice to close every opened file after reading/writing operations. |
3 | read() | read() method is used to read from input file. |
4 | write() | write() method is used for writing to output file. |
CPP File Handling Modes:
Modes are the ways by which we can read/write data to and from the files. C++ allows to use multiple file modes in single file open method.
Sr. | File Mode | Use/Description | Syntax |
1 | out | out mode is used to write data on the file. It open file and start writing in file from begining. | ios::out |
2 | in | in file mode is used as input mode. Input means reading data from file. | ios::in |
3 | app | app mode stands for append mode it open file for output and write data at the end of file. | ios::app |
4 | binary | binary mode is used to open file in binary mode. It can be used with ios::in or ios::out mode. | ios::binary |
5 | ate | ate file mode is used to write/output data at the end of opened file. | ios::ate |
6 | trunc | ios::trunc file mode is used to empty the file. | ios::trunc |
7 | noreplace | noreplace open file if it is not already exist on system. | ios::noreplace |
8 | nocreate | nocreate file handling mode only open some specified file if it already exist. | ios::nocreate |
Difference between app and ate in c++
The difference between ate and app file modes in C++ is that app file opening mode moves the cursor/pointer to the end of file before every write/output operations. While ate opening mode move to the end of file only one time when the file is opening.
So that if multiple object are appending the single file using ate mode then there may be data synchronization issue raise.
Reading File using gtline() function:
In cpp we can also we can also read file line by line.
Example:
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
//standard namespace
using namespace std;
int main () {
// string type variable to read line
string line;
// opening file
ifstream myfile ("d://testFile.txt",ios::in);
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line <<endl;
}
myfile.close(); //successfully closing file
} else {
cout << "File cannot be opened";
}
return 0;
}
Output:
12
33
7
10
--------------------------------
Process exited after 0.02571 seconds with return value 0
Press any key to continue . . .