File handling in C++
Files are important feature in any programming language. File handling refers to reading and writing information in the files. Files have some formats like .txt,.csv and so on.
C++ has lot of standard library files to handles file
management.
Eg: <fstream> header file has ofstream, ifstream,fstream.
It also has ifstream(input file stream) and ofstream(output file stream).
Let us create objects and open the file as follows…
Eg:
‘ifstream’ : ifstream filein("sample.txt");
‘ofstream’ : ofstream fileout("sample.txt");
Where filein ,fileout are objects accordingly.
If you are using ‘fstream’, it needs to open a file like
this.
‘fstream fstr("sample.text", mode);’
Here, fstr is the object of fstream. “sample.txt” is the
file name. Mode is the purpose of
operation going to be performed in the file. It has variety of types.
Modes:
‘ios::app’ – append the contents to the end of file.
‘ios::ate’ - The
control starts with end of the file.
‘ios::binary’ – it deals with binary data.
‘ios::in’ – it is used to read a file.
‘ios::out’ – it is used to writing.
‘ios::trunc’ – it is used for truncation.
Let us create a C++ program to perform file handling.
C++ Program: To write contents to a file
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream
fi("happy.txt"); // This opens a file for writing
if (fi.is_open()) {
fi <<
"It is a good day to start with:" << endl; // Write the
contents to the file
fi <<
"This is a test file." << endl;
fi.close(); //
Close the file object
cout <<
"The written process is completed" << endl;
} else {
cout <<
"Unable to open the file ." << endl;
}
return 0;
}
Output:
The written process is completed
Happy.txt
It is a good day to start with:
This is a test file.
C++ Program: To read the contents in the file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream fin("happy.txt"); // It Opens a file
in read mode
if (fin.is_open()) {
string str;
while (getline(fin, str) ){ // Read the content
line by line
cout << str << endl; // Print the contents
in the output screen
}
fin.close(); // Close the file
} else {
cout << "Unable to open the file " <<
endl;
}
return 0;
}
Output:
It is a good day to start with:
This is a test file.
These are the two methods in file handling. Hope, you
understood the concept. Try it with other texts. Keep Coding!!!
Comments
Post a Comment