TalentJR

🧩 C++ programming tutorial for beginners · Class 11 · Lesson 11 of 18 · Free

File I/O in C++ – Read and Write Files with fstream

⏱ About 35 minutes · ▶ run real C++ here — nothing to install · no sign-in

In this lesson you will

  • Write text to a file with ofstream and check that it opened
  • Read a file line by line with getline and word by word with >>
  • Append to a file and split comma-separated lines with stringstream

Your class teacher types 40 students' marks into a program. She closes it, and every mark is gone. Variables live only while the program runs. Files keep data safe after the program ends, so the next run can read it again.

How do you write to a file in C++ with ofstream?

C++ talks to files through streams, from the <fstream> header. ofstream (output file stream) writes to a file. You use << on it exactly like cout.

Opening an ofstream creates the file. If the file already exists, its old contents are erased. Always check that the file opened: if (!out) means it failed.

Here the program writes three lines, closes the file, and then reads it back so you can see it. Try it: add a fourth student and run again.

🧩 C++ — you can edit this code
Output
File has: Riya 92
File has: Aman 75
File has: Sara 88

💡 close() pushes the last data into the file. A stream also closes by itself at the end of its block.

How do you read a file line by line in C++?

ifstream (input file stream) reads from a file. getline(in, line) reads one whole line, spaces included, into a string.

getline returns the stream. In a while condition the stream counts as true while reading works, and false at the end of the file. So the loop stops by itself.

This example reads attendance.txt, a file that is already in the program's folder. Try it: change the file name to attendence.txt and see the error message.

🗂️ attendance.txt — a file your program can open
Monday present
Tuesday present
Wednesday absent
Thursday present
Friday present
🧩 C++ — you can edit this code
Output
1. Monday present
2. Tuesday present
3. Wednesday absent
4. Thursday present
5. Friday present
Present 4 of 5 days

How do you read numbers and words from a file with >> in C++?

The >> operator reads one word or number at a time and skips spaces and line breaks, just like cin >>.

while (in >> name >> marks) reads a name and a number again and again. It stops at the end of the file, or when the text cannot be read as a number.

Reading into int turns the text "92" into the number 92, so you can add and compare it. Try it: add "Dev 99" to the file box and run again.

🗂️ marks.txt — a file your program can open
Riya 92
Aman 75
Sara 88
Kabir 64
🧩 C++ — you can edit this code
Output
Students: 4
Average: 79.75
Topper: Riya (92)

How do you add to a file without deleting it in C++ (append mode)?

Opening with a plain ofstream erases the file first. To add lines at the end, open it in append mode: ofstream out("log.txt", ios::app);

ios::app is a mode flag. It means "keep what is there and write after it". This is how a canteen app could keep a daily log of orders.

Try it: add a second line out << "09:00 Dosa\n"; and run again. Then remove , ios::app and see the old orders vanish.

🗂️ orders.txt — a file your program can open
08:10 Idli
08:25 Poha
🧩 C++ — you can edit this code
Output
08:10 Idli
08:25 Poha
08:40 Upma
3 orders today

💡 The extra { } block makes the ofstream close before we read the file back.

How do you read a CSV file in C++?

CSV means comma-separated values. Each line is one record, like "Riya,10,1500". Spreadsheets can save files in this format.

Read each line with getline. Then put the line into a stringstream (header <sstream>). A stringstream lets you read from a string as if it were a file.

getline(ss, part, ',') reads up to the next comma. For the numbers, read the last parts with >>. Try it: add a student who paid 0 and run again.

🗂️ fees.csv — a file your program can open
Riya,10,1500
Aman,10,0
Sara,11,1800
Kabir,11,1800
🧩 C++ — you can edit this code
Output
Riya (Class 10): Rs 1500
Aman (Class 10): Rs 0
Sara (Class 11): Rs 1800
Kabir (Class 11): Rs 1800
Total collected: Rs 5100

🤔 Predict the output

Think like C++: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

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

int main() {
    {
        ofstream out("n.txt");
        out << "10\n20\n30\n";
    }
    ifstream in("n.txt");
    int x = 0, sum = 0;
    while (in >> x) {
        sum += x;
    }
    cout << sum << "\n";
    return 0;
}

Question 2. What does this print?

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

int main() {
    { ofstream out("log.txt"); out << "a\n"; }
    { ofstream out("log.txt"); out << "b\n"; }
    { ofstream out("log.txt", ios::app); out << "c\n"; }
    ifstream in("log.txt");
    string line;
    while (getline(in, line)) {
        cout << line;
    }
    cout << "\n";
    return 0;
}

Question 3. How many times does the loop run?

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

int main() {
    { ofstream out("t.txt"); out << "Riya Sharma\nAman Gupta\n"; }
    ifstream in("t.txt");
    string word;
    int count = 0;
    while (in >> word) {
        count++;
    }
    cout << count << "\n";
    return 0;
}

🧩 Your challenge

The file fees.txt has one student per line: name, fee and paid or unpaid. Read it, print the names of students who have NOT paid, and the total fee collected from those who paid. Then write that total into summary.txt and read summary.txt back to show it. Expected output: Unpaid: Aman Unpaid: Kabir Collected: Rs 4800 summary.txt says: Collected Rs 4800

Expected output :
Unpaid: Aman
Unpaid: Kabir
Collected: Rs 4800
summary.txt says: Collected Rs 4800
🗂️ fees.txt — a file your program can open
Riya 1500 paid
Aman 1500 unpaid
Sara 1800 paid
Kabir 1800 unpaid
Meera 1500 paid
🧩 C++ — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

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

int main() {
    ofstream out("notes.txt");
    out << "Riya 92\n";
    out << "Aman 75\n";

    ifstream in("notes.txt");
    string line;
    int count = 0;
    while (getline(in, line)) {
        count++;
    }
    cout << "Lines read: " << count << "\n";
    return 0;
}

Compiles and runs, but prints: Lines read: 0 ⏎

✅ Right

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

int main() {
    ofstream out("notes.txt");
    out << "Riya 92\n";
    out << "Aman 75\n";
    out.close();                 // save everything first

    ifstream in("notes.txt");
    string line;
    int count = 0;
    while (getline(in, line)) {
        count++;
    }
    cout << "Lines read: " << count << "\n";
    return 0;
}

ofstream keeps text in a memory buffer and writes it to the file later. Reading before close() (or flush()) can find an empty file.

❌ Wrong

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

void logOrder(const string& item) {
    ofstream out("orders.txt");
    out << item << "\n";
}

int main() {
    logOrder("Idli");
    logOrder("Dosa");
    ifstream in("orders.txt");
    string line;
    while (getline(in, line)) {
        cout << line << "\n";
    }
    return 0;
}

Compiles and runs, but prints: Dosa ⏎

✅ Right

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

void logOrder(const string& item) {
    ofstream out("orders.txt", ios::app);
    out << item << "\n";
}

int main() {
    logOrder("Idli");
    logOrder("Dosa");
    ifstream in("orders.txt");
    string line;
    while (getline(in, line)) {
        cout << line << "\n";
    }
    return 0;
}

A plain ofstream erases the file each time it opens, so only the last order survives. Use ios::app to add to the end.

❌ Wrong

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

int main() {
    { ofstream out("book.txt"); out << "3\nWings of Fire\n"; }
    ifstream in("book.txt");
    int copies = 0;
    string title;
    in >> copies;
    getline(in, title);
    cout << copies << " copies of [" << title << "]\n";
    return 0;
}

Compiles and runs, but prints: 3 copies of [] ⏎

✅ Right

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

int main() {
    { ofstream out("book.txt"); out << "3\nWings of Fire\n"; }
    ifstream in("book.txt");
    int copies = 0;
    string title;
    in >> copies;
    in.ignore();                 // skip the leftover newline
    getline(in, title);
    cout << copies << " copies of [" << title << "]\n";
    return 0;
}

>> stops before the newline after 3. getline then reads that empty rest of the line. Call in.ignore() to skip the newline first.

📌 Remember

  • Include <fstream>: ofstream writes files, ifstream reads them.
  • Always check the stream: if (!in) means the file did not open.
  • getline reads a whole line; >> reads one word or number and skips spaces.
  • A plain ofstream erases the file; ios::app adds to the end.
  • Close (or end the block of) an ofstream before reading the same file.
  • stringstream with getline(ss, part, ',') splits CSV lines.

Finished the quiz and the challenge?

Questions students ask

What is the difference between ifstream, ofstream and fstream?

ifstream only reads, ofstream only writes, and fstream can do both. Most small programs use ifstream and ofstream because they are simpler and safer.

Why does my C++ program not find the file?

The file name is looked up in the program's working folder. Check the spelling, the extension and the folder. Always test if (!in) and print a clear message.

Do I need to call close() in C++?

Not always. A file stream closes itself when it goes out of scope (its destructor runs, Lesson 7). Call close() when you want to read the file again in the same block.

How do I read a whole line with spaces in C++?

Use getline(in, line). The >> operator stops at the first space, so it reads only one word.