Loading lessons...
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 classes
| Class | Derived from | Used for |
|---|---|---|
ifstream | istream | input from a file (reading) |
ofstream | ostream | output to a file (writing) |
fstream | iostream | both reading and writing |
filebuf | streambuf | the 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:
| Way | Example | Best for |
|---|---|---|
| Using the constructor | ofstream 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.
#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:
Pen costs 10
Pencil costs 5
Eraser costs 3
Total = 183. 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.
| Mode | Meaning |
|---|---|
ios::in | open for reading (default for ifstream) |
ios::out | open for writing (default for ofstream); an existing file is truncated |
ios::app | append: all output goes to the end of the file |
ios::ate | open and go to the end of the file, but writing is allowed anywhere |
ios::trunc | delete the contents if the file exists |
ios::binary | binary 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::app | ios::ate |
|---|---|
| writing is only at the end | starts at the end, but the file pointer can be moved and data written anywhere |
| used for adding records to a log | used for reading/updating a file starting from its end |
#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:
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:
| Method | Example |
|---|---|
| test the stream in a condition | while (in >> x) or while (getline(in, s)): false when a read fails at EOF |
| test the stream object | while (in): a stream converts to false when an error or EOF occurred |
the eof() function | while (!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
#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:
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.
#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:
Capital of India is New Delhi
Capital of Japan is Tokyo
Capital of France is Paris6. File Pointers and Random Access
Every file stream has two file pointers:
| Pointer | Used by | Moved by | Position read by |
|---|---|---|---|
| get pointer (input) | reading | seekg() | tellg() |
| put pointer (output) | writing | seekp() | tellp() |
seekg(offset, reference) moves the get pointer offset bytes from a reference position:
| Reference | Meaning |
|---|---|
ios::beg | from the beginning of the file |
ios::cur | from the current position |
ios::end | from the end of the file |
| Call | Moves 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) |
#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:
file size = 10 bytes
byte 3 = D
second last = I
now: zBCDEFGHIJRandom 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.
| Function | Returns 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 |
!stream | same as fail() |
#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:
Error: cannot open no_such_file.txt
sum of squares = 55
eof() = 1, fail() = 1At 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 file | Binary file |
|---|---|
| data stored as readable characters | data stored exactly as in memory (raw bytes) |
written with <<, read with >>, getline | written 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.
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 withclose()(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/tellgmove/report the get pointer,seekp/tellpthe put pointer, relative toios::beg,ios::cur,ios::end.
📝 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 theitems.txtprogram. - Q2. Explain the different file modes. Differentiate between
ios::appandios::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()andtellp()with a program. (10 Marks) - Write: the pointer table, the reference positions, the seek examples table, and the
alpha.txtprogram. - Q5. How are errors detected during file operations? (2.5 Marks)
- Q6. Differentiate between text and binary files. (2.5 Marks)