C++ File Handling - Beginner Guide
What is File Handling in C++?
File handling means reading from and writing to files on your computer using a C++ program.
C++ provides classes to create, open, write, read, and close files. These are included in the <fstream>
header.
fstream, ifstream, and ofstream
C++ provides three file stream classes:
1. ifstream - for reading from files
2. ofstream - for writing to files
3. fstream - for both reading and writing
Opening a File - Syntax and Example
Example (writing to a file):
#include <fstream>
ofstream myFile("example.txt");
if (myFile.is_open()) {
myFile << "Hello!";
myFile.close();
Basic File Opening Modes
ios::in - Open for reading
ios::out - Open for writing
C++ File Handling - Beginner Guide
ios::app - Append to end of file
ios::ate - Move to end when opened
ios::trunc - Deletes old content
ios::binary- Binary mode
You can combine modes using | (OR).
Reading from a File - Example
#include <fstream>
ifstream file("example.txt");
string line;
while (getline(file, line)) {
cout << line << endl;
Checking if File is Open
Use .is_open():
if (file.is_open()) {
// ready to use
istream and ostream
istream - input stream (cin, ifstream)
ostream - output stream (cout, ofstream)
C++ File Handling - Beginner Guide
Sequential vs Random Access
Sequential: Reads data one by one from start.
Random: Allows jumping to any position using pointers.
File Pointers Overview
get pointer (for reading): seekg(), tellg()
put pointer (for writing): seekp(), tellp()
Basic File Functions - Syntax
open(): file.open("filename.txt", mode);
close(): file.close();
is_open(): file.is_open()
eof(): file.eof()
get(): file.get(ch);
put(): file.put('A');
getline(): getline(file, str);
seekg(): file.seekg(pos);
seekp(): file.seekp(pos);
tellg(): file.tellg();
tellp(): file.tellp();
Special Explanation: seekg and tellg
seekg(position): Moves the read pointer.
tellg(): Returns current read position.
C++ File Handling - Beginner Guide
Example:
file.seekg(5); file.get(ch); // Reads 6th character
Special Explanation: seekp and tellp
seekp(position): Moves the write pointer.
tellp(): Returns current write position.
Example:
file.seekp(6); file.put('M'); // Overwrites 7th character