File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There are two types of communication takes place program.
- Data transfer between the console unit and program.
- Data transfer between program and disk file.
C++ Standard File Handling Class
C++ contains a set of library classes that handle the file handling methods. These classes include:
- ifstream: this header file is used to read input file stream from the file using istream.
- ofstream: this header file is used to write output file stream into the file using ostream.
- fstream: this header file is used for both input and output operation and inherits all the function of istream and ostream thorough iostream.
The above classes are derived from
fstreambase and from the corresponding
iostream class.
Input and Output Stream
The stream that supplies data from file to program is known as
input stream. Input stream is used to read the file into program.
The stream that supplies data from the program to file is known as
an output stream. The output stream is used to write from the program into file.
C++ file handling header files contain several functions for different operations.
Function |
Description |
open() |
To create a new file as well as open an existing file |
close() |
To close an existing file |
read() |
Read data from the file |
write() |
Write data into the file |
get() |
Read a single character from a file |
put() |
Write a single character into a file |
C++ File Handling Mode Parameter
Mode parameter in the file handling defines the specific purpose for which the file is opened. The mode parameter is always passed as the second parameter in the file handling methods. These modes are:
Mode |
Description |
Ios::in |
Open file in read mode |
Ios::out |
Open file in write mode |
Ios::app |
Append to end of file |
Ios::ate |
Go to end of file on opening |
Ios::trunk |
Delete the content of the file if it exits |
C++ File Handling open() Function
A file must be opened before doing any manipulation over it. The
open() function is used to open a file either for read from or write into a file.
Syntax
file-stream-class file-stream-object;
file-stream-object.open("filename");
Example
ofstream outfile;
outfile . open ("employee.txt");
C++ File Handling open() Function Example
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
// open file employee.txt
myfile.open ("D:/Ashutosh/C++ Tutorial/C++ tutorial/employee.txt");//
check file location
if(myfile.is_open()){
cout<<"File is open"<<endl;
myfile << "Writing into a file.\n";
myfile.close();
}
else{
cout<<"Error in file opening"<<endl;
}
return 0;
}
Output: