FILE INPUT AND OUTPUT OPERATIONS IN C++
Introduction:
C++ allows reading from and writing to files using the fstream library. This is useful for saving data
permanently.
Required Header:
#include <fstream>
File Stream Classes:
- ifstream -> for reading from files
- ofstream -> for writing to files
- fstream -> for both reading and writing
Writing to a File:
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, File Handling in C++!" << endl;
outFile << "This is a second line." << endl;
outFile.close();
} else {
cout << "Unable to open file for writing." << endl;
return 0;
Reading from a File:
Example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile("example.txt");
string line;
if (inFile.is_open()) {
while (getline(inFile, line)) {
cout << line << endl;
inFile.close();
} else {
cout << "Unable to open file for reading." << endl;
return 0;
}
File Opening Modes:
You can specify modes while opening files:
ios::in -> Open for reading
ios::out -> Open for writing
ios::app -> Append to the end
ios::ate -> Go to the end when opening
ios::trunc -> Delete contents if file exists
ios::binary -> Open in binary mode
Example with mode:
ofstream outFile("data.txt", ios::app);
Tips for File Handling:
- Always check if the file is open using is_open().
- Use getline() to read full lines including spaces.
- Close files after operations with close().
- File operations can be used to save and retrieve user or program data.
Summary:
File handling in C++ is essential for creating programs that require data storage and retrieval. The
fstream library makes it simple and powerful.