Lesson 36 +40 XP

Streams and Files: File Operations in C++

Streams and Files: File Operations in C++

Data in variables disappears when a program ends. To keep it, programs store it in files on disk.

C++ handles files with the same stream idea as console I/O: a file stream is connected to a file, and <<, >>, get, getline and the other functions work on it exactly as they work on cout and cin. This lesson covers opening and closing files, file modes, reading and writing text, detecting end of file, file pointers and random access, and error handling.

1. File Stream Classes

The file stream classes are declared in <fstream>.

File stream classes derive from the console stream classesFile stream classes derive from the console stream classes

ClassDerived fromUsed for
ifstreamistreaminput from a file (reading)
ofstreamostreamoutput to a file (writing)
fstreamiostreamboth reading and writing
filebufstreambufthe buffer that does the actual file I/O

Because they inherit from istream and ostream, every console I/O feature (operators, manipulators, getline) works with files too.

2. Opening and Closing a File

A file can be opened in two ways:

WayExampleBest for
Using the constructorofstream out("marks.txt");one file per stream
Using open()ofstream out; out.open("marks.txt");opening several files, one after another, with the same stream

A file is closed with close(). It is also closed automatically when the stream object is destroyed (its destructor runs), but closing explicitly releases the file as soon as you are done.

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

int main() {
    // writing: open with the constructor
    ofstream outf("items.txt");
    outf << "Pen 10" << endl;
    outf << "Pencil 5" << endl;
    outf << "Eraser 3" << endl;
    outf.close(); // disconnect the file

    // reading: open with open()
    ifstream inf;
    inf.open("items.txt");
    char name[20];
    int cost;
    int total = 0;
    while (inf >> name >> cost) { // false at the end of the file
        cout << name << " costs " << cost << endl;
        total = total + cost;
    }
    inf.close();
    cout << "Total = " << total << endl;
    return 0;
}

Output:

OUTPUT
Pen costs 10
Pencil costs 5
Eraser costs 3
Total = 18

3. File Modes

open() and the constructors take an optional second argument, the file mode, which says how the file is to be used. Several modes are combined with the bitwise OR operator (one vertical bar), e.g. ios::out | ios::app.

ModeMeaning
ios::inopen for reading (default for ifstream)
ios::outopen for writing (default for ofstream); an existing file is truncated
ios::appappend: all output goes to the end of the file
ios::ateopen and go to the end of the file, but writing is allowed anywhere
ios::truncdelete the contents if the file exists
ios::binarybinary mode: no translation of newline characters
ios::nocreate(pre-standard) fail if the file does not exist
ios::noreplace(pre-standard) fail if the file already exists
ios::appios::ate
writing is only at the endstarts at the end, but the file pointer can be moved and data written anywhere
used for adding records to a logused for reading/updating a file starting from its end
C++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream log("log.txt"); // ios::out: create / truncate
    log << "Line 1" << endl;
    log.close();

    log.open("log.txt", ios::out | ios::app); // append mode
    log << "Line 2 (appended)" << endl;
    log.close();

    ifstream in("log.txt");
    string line;
    while (getline(in, line)) { // read line by line
        cout << line << endl;
    }
    return 0;
}

Output:

OUTPUT
Line 1
Line 2 (appended)

4. Detecting the End of File

A program reading a file must stop at its end. There are several ways:

MethodExample
test the stream in a conditionwhile (in >> x) or while (getline(in, s)): false when a read fails at EOF
test the stream objectwhile (in): a stream converts to false when an error or EOF occurred
the eof() functionwhile (!in.eof()): true after a read has hit the end

Testing the read itself (the first method) is safest. With while (!in.eof()), the loop body runs once more after the last item, because eof() becomes true only after a read fails.

Character-by-character copy

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

int main() {
    ofstream make("source.txt");
    make << "C++ files\nare streams.\n";
    make.close();

    ifstream src("source.txt");
    ofstream dst("copy.txt");
    char ch;
    int count = 0, lines = 0;
    while (src.get(ch)) { // get() reads every character, spaces too
        dst.put(ch);
        count++;
        if (ch == '\n') {
            lines++;
        }
    }
    src.close();
    dst.close();

    cout << "Copied " << count << " characters in " << lines << " lines" << endl;
    ifstream check("copy.txt");
    while (check.get(ch)) {
        cout << ch;
    }
    return 0;
}

Output:

OUTPUT
Copied 23 characters in 2 lines
C++ files
are streams.

5. Working with Multiple Files

Two files can be open at once with two streams: for example, reading one file while writing another, or reading two files alternately.

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

int main() {
    ofstream c("country.txt"), p("capital.txt");
    c << "India\nJapan\nFrance\n";
    p << "New Delhi\nTokyo\nParis\n";
    c.close();
    p.close();

    ifstream fin1("country.txt"), fin2("capital.txt");
    char line[40];
    for (int i = 0; i < 3; i++) {
        fin1.getline(line, 40);
        cout << "Capital of " << line;
        fin2.getline(line, 40);
        cout << " is " << line << endl;
    }
    return 0;
}

Output:

OUTPUT
Capital of India is New Delhi
Capital of Japan is Tokyo
Capital of France is Paris

6. File Pointers and Random Access

Every file stream has two file pointers:

PointerUsed byMoved byPosition read by
get pointer (input)readingseekg()tellg()
put pointer (output)writingseekp()tellp()

seekg(offset, reference) moves the get pointer offset bytes from a reference position:

ReferenceMeaning
ios::begfrom the beginning of the file
ios::curfrom the current position
ios::endfrom the end of the file
CallMoves the get pointer to
fin.seekg(0, ios::beg)the start
fin.seekg(m, ios::beg)byte m (the (m + 1)-th byte)
fin.seekg(m, ios::cur)m bytes forward from here
fin.seekg(-m, ios::cur)m bytes backward from here
fin.seekg(0, ios::end)the end (then tellg() gives the file size)
C++
#include <iostream>
#include <fstream>
using namespace std;

int main() {
    fstream f("alpha.txt", ios::out | ios::in | ios::trunc); // read and write
    f << "ABCDEFGHIJ";

    f.seekg(0, ios::end);
    cout << "file size = " << f.tellg() << " bytes" << endl;

    char ch;
    f.seekg(3, ios::beg); // 4th character
    f.get(ch);
    cout << "byte 3 = " << ch << endl;

    f.seekg(-2, ios::end); // second last character
    f.get(ch);
    cout << "second last = " << ch << endl;

    f.seekp(0, ios::beg); // overwrite the first character
    f.put('z');
    f.seekg(0, ios::beg);
    char all[11];
    f.read(all, 10);
    all[10] = '\0';
    cout << "now: " << all << endl;
    return 0;
}

Output:

OUTPUT
file size = 10 bytes
byte 3 = D
second last = I
now: zBCDEFGHIJ

Random access is what makes it possible to update one record in the middle of a file without rewriting the whole file (Lesson 37).

7. Error Handling During File Operations

Things can go wrong: the file may not exist, the disk may be full, a name may be invalid. Always check that the file opened before using it.

FunctionReturns true when
is_open()the stream is connected to a file
good()no error has occurred
fail()an operation failed (e.g. the file could not be opened, or a read failed)
bad()a serious error occurred
eof()the end of the file was reached
!streamsame as fail()
C++
#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream in("no_such_file.txt");
    if (!in) { // or: if (!in.is_open())
        cout << "Error: cannot open no_such_file.txt" << endl;
    }

    ofstream out("numbers.txt");
    for (int i = 1; i <= 5; i++) {
        out << i * i << " ";
    }
    out.close();

    ifstream nums("numbers.txt");
    if (nums.is_open()) {
        int x, sum = 0;
        while (nums >> x) {
            sum = sum + x;
        }
        cout << "sum of squares = " << sum << endl;
        cout << "eof() = " << nums.eof() << ", fail() = " << nums.fail() << endl;
    }
    return 0;
}

Output:

OUTPUT
Error: cannot open no_such_file.txt
sum of squares = 55
eof() = 1, fail() = 1

At the end, both eof() and fail() are true: the last attempted read hit the end of the file and therefore failed.

8. Text Files vs Binary Files

Text fileBinary file
data stored as readable charactersdata stored exactly as in memory (raw bytes)
written with <<, read with >>, getlinewritten with write(), read with read()
numbers are converted to and from text (slower, may lose precision)no conversion (faster, exact)

↔ \r on Windows) | no translation (open with ios::binary`) |

Binary files and writing whole objects are covered in the next lesson.

💡 Tip

Key points to remember

  • <fstream>: ifstream (read), ofstream (write), fstream (both); they inherit all console I/O features.
  • Open with the constructor or open(); close with close() (or let the destructor do it).
  • Modes: in, out, app, ate, trunc, binary, combined with the bitwise OR operator.
  • Read until a read fails: while (in >> x), while (getline(in, s)), while (in.get(ch)).
  • seekg/tellg move/report the get pointer, seekp/tellp the put pointer, relative to ios::beg, ios::cur, ios::end.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Explain the file stream classes. How is a file opened and closed in C++? (5 Marks)
  • Write: the class table and diagram, the two ways of opening, close(), and the items.txt program.
  • Q2. Explain the different file modes. Differentiate between ios::app and ios::ate. (5 Marks)
  • Q3. Write a program to copy the contents of one file into another, counting characters and lines. (5 Marks)
  • Q4. What are file pointers? Explain seekg(), seekp(), tellg() and tellp() with a program. (10 Marks)
  • Write: the pointer table, the reference positions, the seek examples table, and the alpha.txt program.
  • Q5. How are errors detected during file operations? (2.5 Marks)
  • Q6. Differentiate between text and binary files. (2.5 Marks)