File I/O & Streams (fstream)

ফাইল I/O — fstream

Read: ~25 min 12 practice problems

1. Reading a Text File

read.cpp
#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream in("data.txt");
    if (!in) { std::cerr << "open failed\n"; return 1; }

    std::string line;
    while (std::getline(in, line)) {
        std::cout << line << "\n";
    }
}

2. Writing a Text File

write.cpp
#include <fstream>

int main() {
    std::ofstream out("out.txt");
    out << "Hello\n";
    out << 42 << " " << 3.14 << "\n";
    // auto-closes on scope exit (RAII)
}
Append mode std::ofstream out(path, std::ios::app);

3. Read Whole File

whole.cpp
#include <fstream>
#include <sstream>
#include <string>

std::string readAll(const std::string& path) {
    std::ifstream in(path);
    std::stringstream ss;
    ss << in.rdbuf();
    return ss.str();
}

4. Binary I/O

binary.cpp
#include <fstream>
#include <vector>

int main() {
    std::vector<int> data = {1, 2, 3, 4, 5};

    std::ofstream out("data.bin", std::ios::binary);
    out.write(reinterpret_cast<const char*>(data.data()),
              data.size() * sizeof(int));
}

5. std::filesystem (C++17)

fs.cpp
#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    if (fs::exists("data.txt"))
        std::cout << "size = " << fs::file_size("data.txt") << "\n";

    fs::create_directory("newdir");
    for (const auto& entry : fs::directory_iterator("."))
        std::cout << entry.path() << "\n";
}

6. Practice Problems

  1. Open a file and check failure.
    ✨ Show Answer
    std::ifstream in("x.txt");
    if (!in) std::cerr << "failed\n";
  2. Count lines in a file.
    ✨ Show Answer
    int n = 0;
    std::string line;
    while (std::getline(in, line)) ++n;
  3. Append to a file.
    ✨ Show Answer
    std::ofstream out("log.txt", std::ios::app);
    out << "line\n";
  4. Read all integers from a file into a vector.
    ✨ Show Answer
    std::vector<int> v;
    int x;
    while (in >> x) v.push_back(x);
  5. Why use binary mode?
    ✨ Show Answer

    Bytes are written exactly as in memory. Text mode may translate \n on Windows. For binary data (images, structs), use binary mode.

  6. Get file size with filesystem.
    ✨ Show Answer
    auto sz = std::filesystem::file_size(path);
  7. List all files in a directory.
    ✨ Show Answer
    for (const auto& e : std::filesystem::directory_iterator(path))
        std::cout << e.path() << "\n";
  8. Read a file into a string in one shot.
    ✨ Show Answer

    See section 3.

  9. Why don't you need fclose?
    ✨ Show Answer

    RAII. The fstream's destructor closes the file. You may call close() manually if you want, but normally just let the scope end.

  10. Recursive directory listing.
    ✨ Show Answer
    for (const auto& e : std::filesystem::recursive_directory_iterator(path)) ...
  11. Write a struct to a binary file.
    ✨ Show Answer
    out.write(reinterpret_cast<const char*>(&obj), sizeof(obj));

    Only safe for plain-old-data types — pointers and dynamic members would be invalid.

  12. Move a file with filesystem.
    ✨ Show Answer
    std::filesystem::rename("old.txt", "new.txt");

Summary

std::ifstream / std::ofstream handle text I/O. Use binary mode (std::ios::binary) for non-text. std::filesystem (C++17) provides path manipulation and FS queries with cross-platform ergonomics. RAII closes files automatically.

Next Module → Build Systems & Modern CMake.