C++ fstream Library (File Streams)

Welcome to The Coding College! This tutorial focuses on the fstream library in C++, which is used for file handling operations such as reading, writing, and modifying files.

What is the fstream Library?

The fstream library is part of the C++ Standard Library and provides tools to handle file input and output. It includes three main classes for file handling:

  • ifstream: Input file stream (for reading files).
  • ofstream: Output file stream (for writing to files).
  • fstream: File stream (for both reading and writing).

To use these classes, include the following directive in your code:

#include <fstream>

File Stream Classes

ClassDescription
ifstreamReads data from files.
ofstreamWrites data to files.
fstreamPerforms both input and output on files.

Basic File Operations

Opening a File

You can open a file in two ways:

  • Directly in the constructor:
ifstream file("example.txt");
  • Using the open() method:
ifstream file;
file.open("example.txt");

Closing a File

Always close a file after operations to free up system resources:

file.close();

Writing to a File (ofstream)

Example: Writing Data to a File

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

int main() {
    ofstream outFile("example.txt"); // Open file for writing

    if (outFile.is_open()) {
        outFile << "Hello, World!" << endl;
        outFile << "Welcome to file handling in C++." << endl;
        outFile.close(); // Close the file
        cout << "Data written to file successfully!" << endl;
    } else {
        cout << "Unable to open file for writing." << endl;
    }

    return 0;
}

Output in the file example.txt:

Hello, World!
Welcome to file handling in C++.

Reading from a File (ifstream)

Example: Reading Data from a File

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

int main() {
    ifstream inFile("example.txt"); // Open file for reading
    string line;

    if (inFile.is_open()) {
        while (getline(inFile, line)) {
            cout << line << endl; // Display the file's contents
        }
        inFile.close(); // Close the file
    } else {
        cout << "Unable to open file for reading." << endl;
    }

    return 0;
}

Output on the console:

Hello, World!
Welcome to file handling in C++.

Reading and Writing (fstream)

Example: Appending Data to a File

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

int main() {
    fstream file("example.txt", ios::in | ios::out | ios::app); // Open file for reading and writing

    if (file.is_open()) {
        file << "Appending new content to the file." << endl; // Append data
        file.seekg(0, ios::beg); // Move to the beginning of the file

        string line;
        while (getline(file, line)) {
            cout << line << endl; // Display the updated content
        }

        file.close(); // Close the file
    } else {
        cout << "Unable to open file for reading and writing." << endl;
    }

    return 0;
}

Updated file content (example.txt):

Hello, World!
Welcome to file handling in C++.
Appending new content to the file.

File Modes

The fstream library supports several file modes. You can combine these modes using the bitwise OR operator (|).

ModeDescription
ios::inOpen file for reading.
ios::outOpen file for writing.
ios::appAppend data to the end of the file.
ios::truncTruncate the file if it exists.
ios::binaryOpen file in binary mode.

Example: Using File Modes

fstream file("data.txt", ios::out | ios::app);

Checking File Status

Use these member functions to check the file’s status:

  • is_open(): Checks if the file is successfully opened.
  • eof(): Checks if the end of the file has been reached.
  • fail(): Checks for an I/O operation failure.

Error Handling

Example: Handling File Opening Errors

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

int main() {
    ifstream inFile("nonexistent.txt");

    if (!inFile) {
        cerr << "Error: File not found!" << endl;
    } else {
        cout << "File opened successfully!" << endl;
    }

    return 0;
}

Output:

Error: File not found!

Practical Use Case

Example: Writing and Reading Student Records

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

int main() {
    string name;
    int age;

    // Write to file
    ofstream outFile("students.txt");
    if (outFile.is_open()) {
        outFile << "Alice 21" << endl;
        outFile << "Bob 22" << endl;
        outFile.close();
    }

    // Read from file
    ifstream inFile("students.txt");
    if (inFile.is_open()) {
        while (inFile >> name >> age) {
            cout << "Name: " << name << ", Age: " << age << endl;
        }
        inFile.close();
    }

    return 0;
}

Output:

Name: Alice, Age: 21
Name: Bob, Age: 22

Summary

  • The fstream library in C++ simplifies file handling tasks.
  • Use ofstream for writing, ifstream for reading, and fstream for both operations.
  • Always close files after operations to free resources.
  • Handle errors gracefully to ensure robust programs.

Explore More at The Coding College

Learn more about file handling and other advanced programming topics at The Coding College.

Leave a Comment