ifstream


Header: <ifstream>

The <ifstream> header is part of the C++ Standard Library's I/O stream classes. It provides the std::ifstream class, which is used for reading from files. This class inherits from std::istream and adds file-specific functionality.

Key Characteristics

Key Components

  1. std::ifstream: The main class for file input operations

Example 1: Basic File Reading

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream file("example.txt");

    if (file.is_open()) {
        std::string line;
        while (std::getline(file, line)) {
            std::cout << line << std::endl;
        }
        file.close();
    } else {
        std::cerr << "Unable to open file" << std::endl;
    }

    return 0;
}

Explanation

Example 2: Reading Formatted Data

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream file("data.txt");

    if (file.is_open()) {
        int id;
        std::string name;
        double score;

        while (file >> id >> name >> score) {
            std::cout << "ID: " << id << ", Name: " << name << ", Score: " << score << std::endl;
        }

        file.close();
    } else {
        std::cerr << "Unable to open file" << std::endl;
    }

    return 0;
}

Explanation

Example 3: Reading Binary Data

#include <iostream>
#include <fstream>
#include <vector>

struct Record {
    int id;
    char name[20];
    double score;
};

int main() {
    std::ifstream file("records.bin", std::ios::binary);

    if (file.is_open()) {
        Record record;
        std::vector<Record> records;

        while (file.read(reinterpret_cast<char*>(&record), sizeof(Record))) {
            records.push_back(record);
        }

        file.close();

        for (const auto& r : records) {
            std::cout << "ID: " << r.id << ", Name: " << r.name << ", Score: " << r.score << std::endl;
        }
    } else {
        std::cerr << "Unable to open file" << std::endl;
    }

    return 0;
}

Explanation

Additional Considerations

Summary

The <ifstream> header and std::ifstream class provide a convenient and type-safe way to read data from files in C++.

Key points to remember:

  1. Use std::ifstream for file input operations
  2. Always check if the file is successfully opened
  3. Can read both text and binary files
  4. Integrates well with other stream operations and C++ I/O facilities
  5. Automatically manages file handles, but manual closing is recommended

By using <ifstream>, C++ developers can easily implement file reading operations, whether for simple text files or more complex binary data structures. It provides a flexible and object-oriented approach to file I/O, consistent with C++'s stream-based input/output philosophy.

Previous Page | Course Schedule | Course Content