C++ File Handling | Text and Binary Files, File Streams, File Pointers


This complete tutorial on C++ File Handling explains how to read from and write to text and binary files using file streams. It also covers file pointer positioning and best practices for safe and efficient file operations in C++.

File Handling – Complete Tutorial

1. What is File Handling?

File handling allows programs to store data persistently in files.

  1. Two main file types: text files and binary files
  2. Uses fstream library: ifstream, ofstream, fstream

2. File Streams

  1. ifstream – input file stream (read files)
  2. ofstream – output file stream (write files)
  3. fstream – read/write files

Example:


#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream outFile("example.txt");
outFile << "Hello File Handling\n";
outFile.close();

ifstream inFile("example.txt");
string line;
while(getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
}

3. Text File Operations

Writing to a text file:


ofstream out("data.txt");
out << "Line 1\n";
out << "Line 2\n";
out.close();

Reading from a text file:


ifstream in("data.txt");
string line;
while(getline(in, line)) {
cout << line << endl;
}
in.close();

4. Binary File Operations

Binary files store data in raw format, suitable for objects or complex data.

Writing binary data:


#include <fstream>
struct Point { int x, y; };
int main() {
Point p = {10, 20};
ofstream out("point.bin", ios::binary);
out.write((char*)&p, sizeof(p));
out.close();
}

Reading binary data:


Point p;
ifstream in("point.bin", ios::binary);
in.read((char*)&p, sizeof(p));
cout << p.x << ", " << p.y << endl;
in.close();

5. File Pointer Positioning

File streams maintain pointers to current read/write positions.

Functions:

  1. seekg() – move get pointer (read)
  2. seekp() – move put pointer (write)
  3. tellg() – get current read position
  4. tellp() – get current write position

Example:


ofstream out("example.txt");
out << "ABCDEFG";
out.seekp(3); // move write pointer to position 3
out << "123"; // overwrites from 4th character
out.close();

Best Practices

  1. Always close file streams after operations
  2. Check file open status with is_open()
  3. Use binary mode for non-text data
  4. Use RAII style (fstream object closes automatically at scope end)
  5. Avoid mixing read/write without proper positioning

Common Mistakes

  1. Forgetting ios::binary for binary files
  2. Not checking if file opened successfully
  3. Using seekg/seekp incorrectly
  4. Mixing ofstream and ifstream for same file without fstream

Summary

In this chapter, you learned about C++ File Handling, including:

  1. File streams (ifstream, ofstream, fstream)
  2. Reading and writing text and binary files
  3. File pointer positioning (seekg, seekp, tellg, tellp)
  4. Best practices and common mistakes

File handling is essential for persistent data storage, logging, and reading/writing structured data in C++ programs.