What is File Handling in C++?

  • File handling means working with files on your computer using a C++ program.
  • Why use it? Programs often need to store data permanently (e.g., save a game’s score, a student’s name, or a list of numbers). Without files, data disappears when the program ends.
  • Types of files: We focus on text files (.txt) for beginners. They store plain text like words and numbers.
  • Deep detail: C++ uses “streams” for input/output. A stream is like a flow of data. For files, we use special stream classes from the <fstream> library.
    • Input: Reading from file to program.
    • Output: Writing from program to file.
  • Real-life example: Imagine a diary app. You write notes (output to file) and read old notes (input from file).

Important Header Files

Always include these at the top of your code:

C++
 
#include <fstream>   // For file handling (ifstream, ofstream)
#include <iostream>  // For cout and cin (to print messages)
#include <string>    // For using strings (optional but helpful for text)
using namespace std; // So you don't have to write "std::" everywhere
 
 
  • Deep detail: <fstream> gives you classes like ifstream and ofstream. Without it, your code won’t compile. using namespace std; makes code shorter but is okay for beginners.

Key Classes for Files

  • ofstream: For writing (output) to a file. Think “o” for output.
  • ifstream: For reading (input) from a file. Think “i” for input.
  • fstream: For both reading and writing in one object. (Beginners: Use separate ifstream/ofstream for simplicity.)
  • Deep detail: These are derived from iostream classes. They handle file operations like opening, closing, and checking errors.

Steps to Work with Files (General Process)

  1. Declare an object: Like ofstream myFile;.
  2. Open the file: Connect your object to a real file on disk.
  3. Check if open: Always verify if it worked (files might not exist or be locked).
  4. Read or Write: Use operators like << (write) or >> (read).
  5. Close the file: Good habit to free resources.
  • Deep detail: Files are opened in “modes” (e.g., read-only, write-only). If not specified, defaults are used. Closing is automatic when program ends, but explicit close prevents issues in big programs.

Writing to a File (Using ofstream)

This saves data from your program to a file.

Basic Steps:

  1. Create ofstream object and open file.
  2. Write data using << (like cout).
  3. Close.

Simple Example: Create a New File and Write Text

C++
 
int main() {
    ofstream myFile("example.txt");  // File name (creates if not exists)

    if (myFile.is_open()) {  // Check if file opened successfully
        myFile << "Hello World!\n";  // Write line 1 (\n for new line)
        myFile << "This is a C++ file handling example.\n";  // Line 2
        myFile << "Your name: Alice\n";  // Line 3

        myFile.close();  // Close the file
        cout << "Data written to file successfully!" << endl;
    } else {
        cout << "Unable to open file!" << endl;
    }

    return 0;
}
 
 
  • What happens: Runs and creates “example.txt” with the text. Open it in Notepad to see.
  • Deep detail: << sends data to the file stream. If file exists, it overwrites (deletes old content). Use \n for new lines, or endl (flushes buffer).

Writing Numbers or User Input

C++
 
int main() {
    ofstream myFile("numbers.txt");

    if (myFile.is_open()) {
        int age = 15;
        string name = "Bob";

        myFile << "Name: " << name << "\n";  // Write string and variable
        myFile << "Age: " << age << "\n";

        // Get input from user and write
        cout << "Enter a message: ";
        string message;
        getline(cin, message);  // Read full line from keyboard
        myFile << "Message: " << message << "\n";

        myFile.close();
    } else {
        cout << "File open failed!" << endl;
    }

    return 0;
}
 
 
  • Deep detail: You can mix text, variables, and user input. Use getline for full sentences (handles spaces).

File Modes for Writing

  • Default: Overwrite existing file.
  • Append mode (add to end without deleting old): Use ios::app.
C++
 
ofstream myFile("example.txt", ios::app);  // Adds to end
 
 
  • Other modes:
    • ios::out: Write (default for ofstream).
    • ios::trunc: Truncate (delete old content, default).
    • ios::ate: Start at end (but can move cursor).
  • Deep detail: Modes are from <ios> (included in fstream). Combine with like ios::out | ios::app.

Writing Loops (e.g., Save a List)

C++
 
int main() {
    ofstream myFile("list.txt");

    if (myFile.is_open()) {
        for (int i = 1; i <= 5; i++) {
            myFile << "Item " << i << "\n";
        }
        myFile.close();
    }
    return 0;
}
 
 
  • Output file: Item 1 to Item 5, each on new line.
  • Deep detail: Loops are great for saving arrays or lists. For binary data (non-text), use ios::binary mode, but skip for beginners.

Reading from a File (Using ifstream)

This gets data from a file into your program.

Basic Steps:

  1. Create ifstream object and open file.
  2. Read data using >> (words/numbers) or getline (full lines).
  3. Close.

Simple Example: Read and Print File Content

C++
 
int main() {
    ifstream myFile("example.txt");  // Must exist, or error

    if (myFile.is_open()) {
        string line;
        while (getline(myFile, line)) {  // Read line by line
            cout << line << endl;  // Print to screen
        }
        myFile.close();
    } else {
        cout << "Unable to open file!" << endl;
    }

    return 0;
}
 
 
  • What happens: Prints the file’s content to console.
  • Deep detail: getline(myFile, line) reads until \n. Loop until end of file (EOF). >> reads words: e.g., myFile >> word;.

Reading Numbers

C++
 
int main() {
    ifstream myFile("numbers.txt");

    if (myFile.is_open()) {
        string nameLabel, name;
        string ageLabel;
        int age;

        myFile >> nameLabel >> name;  // "Name:" and "Bob"
        myFile >> ageLabel >> age;    // "Age:" and 15

        cout << "Read: " << name << " is " << age << " years old." << endl;

        myFile.close();
    }
    return 0;
}
 
 
  • Deep detail: >> skips spaces/whitespaces. Good for structured data. For full lines with spaces, use getline.

File Modes for Reading

  • Default: ios::in (input).
  • Other: ios::ate (start at end), ios::binary (for non-text).
  • Deep detail: If file doesn’t exist, is_open() returns false. Use fail() or eof() for more checks.

Error Handling (Important for Real Programs)

  • Always check is_open() or good().
  • Common errors:
    • File not found: For reading.
    • No permission: Can’t write.
    • Disk full: Write fails.
  • Advanced check:
C++
 
if (myFile.fail()) {
    cout << "Error occurred!" << endl;
}
 
 
  • Deep detail: Use perror(“Error: “) for system error messages. In big programs, use exceptions: myFile.exceptions(ifstream::failbit);.

Reading and Writing Together (Using fstream)

For both in one file:

C++
 
int main() {
    fstream myFile("data.txt", ios::in | ios::out | ios::app);

    if (myFile.is_open()) {
        // Write
        myFile << "New data\n";

        // Reset to start for reading
        myFile.seekg(0, ios::beg);

        // Read
        string line;
        while (getline(myFile, line)) {
            cout << line << endl;
        }
        myFile.close();
    }
    return 0;
}
 
 
  • Deep detail: seekg() moves read position. seekp() for write. Use for editing files.

Advanced Topics (For BS Level or Deeper Understanding)

  • Binary Files: Use ios::binary. Write/read raw data (e.g., structs). Example: myFile.write((char*)&age, sizeof(age));
  • File Positions: tellg() (current read pos), tellp() (write pos).
  • Random Access: Jump to any part: myFile.seekg(10); (skip 10 bytes).
  • End of File (EOF): myFile.eof() checks if done reading.
  • Working with Arrays/Structures:
    C++
     
    struct Student { 
    string name;
    int marks;
    }; Student s = {"Charlie", 90}; myFile.write((char*)&s, sizeof(s)); // Binary write
     
     
  • Deep detail: Binary is faster for large data but not human-readable. Text files are easier to debug.

Common Mistakes and Tips

  • Mistake: Forgetting to close file – can lock it.
  • Mistake: Wrong file path (e.g., use full path like “C:\folder\file.txt” if needed).
  • Mistake: Reading non-existent file – always check.
  • Tip: Use relative paths for simple programs (file in same folder).
  • Tip: For big files, read in chunks to save memory.
  • Tip: Test on small files first.
  • Security: Don’t write sensitive data without protection.
  • Deep detail: In real apps, handle multiple files, directories (use <filesystem> in C++17+), or encrypt data.

Practice Exercises

  1. Write a program to save 10 numbers to a file.
  2. Read a file and count words.
  3. Append user input to a log file.
  4. Copy one file to another.

This covers all basics to advanced on file reading/writing in C++. For your website, add images of code output or diagrams of streams. If you need more examples or quizzes, let me know!