LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 26 of 27

File Handling (fstream)

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

Programs & Examples

File Handling (fstream) · Study material

Read a CSV file and write a formatted report

getline with a comma delimiter splits each CSV line; std::format writes an aligned report to a second file, which is then printed with rdbuf().

#include <filesystem>
#include <format>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

struct Row { std::string name; int maths, science; };

int main() {
    const auto in_path  = std::filesystem::temp_directory_path() / "lf_marks.csv";
    const auto out_path = std::filesystem::temp_directory_path() / "lf_report.txt";
    std::ofstream(in_path) << "name,maths,science\nAsha,91,88\nRavi,64,72\nMeena,78,95\n";

    std::ifstream in(in_path);
    std::string line;
    std::getline(in, line);                                   // skip the header
    std::vector<Row> rows;
    while (std::getline(in, line)) {
        std::stringstream ss(line);
        Row r;
        std::string field;
        std::getline(ss, r.name, ',');                        // getline with a delimiter
        std::getline(ss, field, ','); r.maths = std::stoi(field);
        std::getline(ss, field, ','); r.science = std::stoi(field);
        rows.push_back(r);
    }

    {
        std::ofstream out(out_path);
        out << std::format("{:<8}{:>6}{:>9}{:>8}\n", "Name", "Maths", "Science", "Avg");
        for (const auto& r : rows)
            out << std::format("{:<8}{:>6}{:>9}{:>8.1f}\n", r.name, r.maths, r.science, (r.maths + r.science) / 2.0);
    }
    std::ifstream report(out_path);
    std::cout << report.rdbuf();
    report.close();
    std::filesystem::remove(in_path);
    std::filesystem::remove(out_path);
    return 0;
}

Output

Name     Maths  Science     Avg
Asha        91       88    89.5
Ravi        64       72    68.0
Meena       78       95    86.5

Counting lines, words, characters and vowels

The reading-styles example reads the same file four ways, using clear() and seekg(0) to rewind between passes.

Fixed-size binary records with random access

The binary example writes three records and reads the third directly by seeking to 2 × sizeof(Record).

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