File handling
To perform file handling in C++, you can follow these steps:
Include the necessary header file: Begin by including the
<fstream>
header file, which provides the necessary functionalities for file handling in C++.Declare file stream objects: Declare objects of the
ifstream
class to read from a file, or objects of theofstream
class to write to a file. Alternatively, you can use thefstream
class, which can be used for both reading and writing.Open a file: Use the
open()
function of the file stream object to open a file. You need to provide the filename as a parameter to this function. You can specify the file mode as well, such asios::in
for input,ios::out
for output, orios::app
for appending to an existing file.Check if the file is open: After opening the file, you can check if the file is successfully opened or not using the
is_open()
function. It returnstrue
if the file is open andfalse
otherwise.Read from or write to the file: If you opened the file in input mode, you can use functions like
getline()
,>>
, orget()
to read data from the file. If you opened the file in output mode, you can use functions likewrite()
,<<
, orput()
to write data to the file.Close the file: After you finish reading from or writing to the file, use the
close()
function of the file stream object to close the file. This step is important to release the resources associated with the file.
Here is an example of file handling in C++:
#include <fstream>
using namespace std;
int main() {
ofstream outputFile;
outputFile.open("example.txt");
if (outputFile.is_open()) {
outputFile << "This is an example text." << endl;
outputFile.close();
}
ifstream inputFile;
inputFile.open("example.txt");
if (inputFile.is_open()) {
string line;
while (getline(inputFile, line)) {
cout << line << endl;
}
inputFile.close();
}
return 0;
}
In this example, the program opens a file called "example.txt" in output mode, writes a line of text to it, and then closes it. After that, it opens the same file in input mode, reads the content line by line, and prints it to the console.
I hope this explanation helps you understand the basic steps involved in file handling in C++.