LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 26 of 27

File Handling (fstream)

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

File Handling (fstream) · Study material

Make streams throw on errors

By default streams only set flags. Calling exceptions(failbit | badbit) makes them throw std::ios_base::failure, which is handy when a missing or unreadable file should abort an operation.

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

// Ask the stream to THROW instead of silently setting flags
std::string read_config(const std::filesystem::path& p) {
    std::ifstream in;
    in.exceptions(std::ifstream::failbit | std::ifstream::badbit);
    in.open(p);                               // throws std::ios_base::failure if it cannot open
    std::string first;
    std::getline(in, first);
    return first;
}

int main() {
    const auto tmp = std::filesystem::temp_directory_path();
    std::ofstream(tmp / "lf_config.ini") << "theme=dark\n";
    for (const char* name : {"lf_config.ini", "lf_missing.ini"}) {
        try {
            std::string value = read_config(tmp / name);     // may throw: call it before printing
            std::cout << name << ": " << value << '\n';
        } catch (const std::ios_base::failure&) {
            std::cout << name << ": could not be read\n";
        }
    }
    std::filesystem::remove(tmp / "lf_config.ini");
    return 0;
}

Output

lf_config.ini: theme=dark
lf_missing.ini: could not be read

The correct reading loops

std::ifstream in("data.txt");
if (!in) { /* report: could not open */ }

for (std::string line; std::getline(in, line); ) { … }     // ✔ line by line
for (int x; in >> x; ) { … }                               // ✔ number by number
for (char c; in.get(c); ) { … }                            // ✔ every character

while (!in.eof()) {                                        // ✘ checks BEFORE reading:
    std::getline(in, line);                                //   the last line is processed twice,
    process(line);                                         //   and bad data loops forever
}

int age; std::string name;
in >> age;
std::getline(in >> std::ws, name);                         // ✔ skip the newline left by >>

Safe file updates: write a temp file, then rename

namespace fs = std::filesystem;

void save(const fs::path& target, const std::string& data) {
    fs::path tmp = target;
    tmp += ".tmp";
    {
        std::ofstream out(tmp, std::ios::binary);
        out << data;
        if (!out) throw std::runtime_error("write failed");
    }                                   // flushed and closed
    fs::rename(tmp, target);            // replaces the old file in one step:
}                                       // readers never see a half-written file

File handling checklist

  • Check that every file opened; report the path in error messages.
  • Let destructors close files; keep stream objects in the smallest scope.
  • Loop on read operations, not on eof().
  • Choose the mode deliberately: trunc (default), app or in|out.
  • Use binary mode and fixed-size records for raw data; text for human-readable data.
  • Use std::filesystem for paths and directory work.
  • Write to a temporary file and rename it for crash-safe saves.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links