notes.txt holds three lines: "Kerala PSC", "Systems Manager exam" and "100 MCQs", each ending with a newline. What does the get()-based counter of Section 4 print, and why must it use get() rather than >>?
Files keep data after a program ends. C++ uses the fstream classes (ifstream, ofstream, fstream) with open modes, text and binary I/O and seekg/seekp for random access; Java uses reader/writer and stream classes from java.io plus the java.nio.file Files utility.
<fstream>: ifstream (input), ofstream (output), fstream (both), derived from istream / ostream / iostream. Open with the constructor or open(); finish with close().ios::in, ios::out, ios::app (every write at the end), ios::ate (start at the end, may move), ios::trunc, ios::binary; combine them with |.ios::nocreate/noreplace are pre-standard.<<, >> (skips whitespace), get() / put() per character, getline(). Binary I/O: write((char*)&obj, sizeof obj) and read(…).seekg, tellg) and put (seekp, tellp); seekg(off, ios::beg | ios::cur | ios::end). File size = seekg(0, ios::end) then tellg().eof() turns true only after a read fails — loop with while (in >> x), not while (!in.eof()). Other states: fail(), bad(), good(), clear().readLine() → null at end), BufferedWriter, PrintWriter; Scanner parses input.java.nio.file.Files: readAllLines, write, copy, lines.Variables live in RAM and vanish when the program ends. A file is a named collection of data on secondary storage (disk, SSD) that persists between runs. Programs talk to files — and to the keyboard, the screen and network connections — through streams: a stream is a sequence of bytes flowing from a source into the program (an input stream) or from the program to a destination (an output stream).
Files can be processed sequentially — from the first byte to the last, like a cassette — or by random access, jumping straight to a computed byte position, like a CD. Random access is natural for binary files of fixed-size records: record n starts at (n − 1) × record size.
C++ file I/O lives in the header <fstream> and reuses the same class family as cin and cout: ios_base → ios → istream and ostream → iostream. The file classes derive from these, so everything you know about >>, << and getline works on files too. Each file stream owns a filebuf that buffers data between the program and the disk.
| Class | Derived from | Purpose | Default mode |
|---|---|---|---|
| ifstream | istream | Read from a file | ios::in |
| ofstream | ostream | Write to a file | ios::out (which truncates) |
| fstream | iostream | Read and write the same file | ios::in | ios::out |
| filebuf | streambuf | The buffer between a stream and the disk | — |
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ofstream out("marks.txt"); // 1. open through the constructor
out << "Anu 78\n" << "Biju 91\n";
out.close();
ifstream in; // 2. create first, open later
in.open("marks.txt");
if (!in) { // or !in.is_open(): did the open fail?
cerr << "cannot open marks.txt\n";
return 1;
}
string name;
int mark;
while (in >> name >> mark) // >> skips spaces and newlines
cout << name << " scored " << mark << "\n";
} // destructors close any open fileAlways test whether the open succeeded — a missing file or a read-only folder leaves the stream in a failed state, and every later read silently does nothing. A stream converts to false in a condition when it has failed. close() flushes and releases the file; the destructor does it anyway when the stream goes out of scope.
| Mode flag | Meaning |
|---|---|
| ios::in | Open for reading (default for ifstream) |
| ios::out | Open for writing (default for ofstream); truncates unless combined with in or app |
| ios::app | Append: every write goes to the end, wherever the put pointer was moved |
| ios::ate | 'At end': move to the end right after opening, but the pointers may be moved anywhere later |
| ios::trunc | Discard the existing contents |
| ios::binary | Binary mode: no newline translation |
| ios::nocreate, ios::noreplace | Pre-standard (Turbo C++) flags — not part of standard C++ |
Flags are combined with the bitwise OR operator: ofstream logFile("app.log", ios::app); keeps old entries; fstream f("data.dat", ios::in | ios::out | ios::binary); opens an existing binary file for update. Note that in | out without trunc does not create a missing file — the open fails — whereas ios::out alone, or out | app, or in | out | trunc creates it.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
{ ofstream f("log.txt"); f << "line1\n"; } // create (truncate)
{ ofstream f("log.txt", ios::app); f << "line2\n"; } // appended at the end
{ fstream f("log.txt", ios::out | ios::in | ios::ate); // starts at the end ...
f.seekp(0); // ... but may move back
f << "LINE"; } // overwrites "line"
ifstream in("log.txt");
string s;
while (getline(in, s)) cout << s << "\n";
}out << x and in >> x — formatted I/O; >> skips leading whitespace and stops at the next whitespace.in.get(ch) reads every character, spaces and newlines included; out.put(ch) writes one character.in.getline(buf, n) (member, char array) reads up to n − 1 characters or a newline; getline(in, str) (free function) reads a whole line into a std::string.in.ignore(n, '\n') skips input — handy after >> before reading a line.#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
int main() {
ofstream out("notes.txt"); // ios::out | ios::trunc by default
out << "Kerala PSC\n" << "Systems Manager exam\n" << "100 MCQs\n";
out.close();
ifstream in("notes.txt"); // ios::in by default
if (!in) { cerr << "cannot open\n"; return 1; }
char ch;
int chars = 0, words = 0, lines = 0;
bool inWord = false;
while (in.get(ch)) { // get() also returns spaces and newlines
chars++;
if (ch == '\n') lines++;
if (isspace(static_cast<unsigned char>(ch))) inWord = false;
else if (!inWord) { inWord = true; words++; } // a new word starts here
}
cout << chars << " chars, " << words << " words, " << lines << " lines\n";
}A stream records its condition in state bits. eof() is true once a read has hit the end; fail() once an operation failed (end of file, or >> met letters while expecting a number); bad() after a serious error such as a disk failure; good() when none of these is set; clear() resets the bits so the stream can be used again.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream("marks.txt") << "70\n85\n90\n";
ifstream a("marks.txt");
int x, sum = 0, n = 0;
while (!a.eof()) { // WRONG: eof() becomes true only AFTER a read fails
a >> x; // the 4th read fails before any digit: x keeps 90
sum += x; n++;
}
cout << "buggy: n=" << n << " sum=" << sum << "\n";
ifstream b("marks.txt");
sum = 0; n = 0;
while (b >> x) { // RIGHT: test the read itself
sum += x; n++;
}
cout << "correct: n=" << n << " sum=" << sum << "\n";
}Binary I/O copies raw bytes: ostream& write(const char* buf, streamsize n) and istream& read(char* buf, streamsize n). To write an object you pass its address reinterpreted as a byte pointer and its size. This is safe only for plain records — fixed-size members and no pointers: a std::string or char* member would write an address, not the text it points to.
#include <iostream>
#include <fstream>
using namespace std;
struct Student { // fixed size, no pointers: safe to store as raw bytes
int roll;
char name[20];
float mark;
};
int main() {
Student list[3] = {{101, "Anu", 78.5f}, {102, "Biju", 91.0f}, {103, "Chitra", 85.0f}};
fstream f("students.dat", ios::out | ios::in | ios::binary | ios::trunc);
for (const Student& s : list)
f.write(reinterpret_cast<const char*>(&s), sizeof(Student));
cout << "record size " << sizeof(Student) << ", file size " << f.tellp() << "\n";
Student s;
f.seekg(1 * sizeof(Student), ios::beg); // record #2 starts at byte 28
f.read(reinterpret_cast<char*>(&s), sizeof(Student));
cout << s.roll << " " << s.name << " " << s.mark << "\n";
s.mark = 95.0f; // update it in place
f.seekp(1 * sizeof(Student), ios::beg);
f.write(reinterpret_cast<const char*>(&s), sizeof(Student));
f.seekg(0);
while (f.read(reinterpret_cast<char*>(&s), sizeof(Student)))
cout << s.roll << ":" << s.mark << " ";
cout << "\n";
}Every stream keeps two position markers: the get pointer (where the next read happens) and the put pointer (where the next write happens). They advance automatically with each operation and can be moved explicitly. For fstream the two are effectively the same position in practice, so seek before switching between reading and writing.
| Function | Pointer | Meaning |
|---|---|---|
| seekg(pos) | get | Move to absolute byte position pos (counted from the beginning, 0-based) |
| seekg(off, dir) | get | Move off bytes relative to ios::beg, ios::cur or ios::end (off may be negative) |
| tellg() | get | Return the current get position |
| seekp(pos) / seekp(off, dir) | put | Move the put pointer the same way |
| tellp() | put | Return the current put position |
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream out("nums.dat", ios::out | ios::binary);
for (int i = 1; i <= 5; i++) {
int sq = i * i; // 1 4 9 16 25
out.write(reinterpret_cast<const char*>(&sq), sizeof(sq));
}
out.close();
ifstream in("nums.dat", ios::in | ios::binary);
in.seekg(0, ios::end); // jump to the end
cout << "size = " << in.tellg() << " bytes\n"; // 5 x 4 = 20
in.seekg(2 * sizeof(int), ios::beg); // skip 2 records
int v;
in.read(reinterpret_cast<char*>(&v), sizeof(v));
cout << "3rd record = " << v << ", get pointer now at " << in.tellg() << "\n";
in.seekg(-static_cast<int>(sizeof(int)), ios::end); // 4 bytes before the end
in.read(reinterpret_cast<char*>(&v), sizeof(v));
cout << "last record = " << v << "\n";
}| Class | Kind | Typical use |
|---|---|---|
| FileReader / FileWriter | Character streams | Simple text files; new FileWriter(name, true) appends |
| BufferedReader / BufferedWriter | Buffered character streams | readLine() returns null at the end; newLine() writes a line separator |
| FileInputStream / FileOutputStream | Byte streams | Images and other binary data; read() returns −1 at the end |
| PrintWriter | Formatted character output | println() and printf() into a file |
| Scanner (java.util) | Parsing reader | nextInt(), nextLine(), hasNext() over a File |
| Files and Path (java.nio.file, Java 7) | Utility methods | readAllLines, write, copy, lines; readString (Java 11) |
import java.io.*;
import java.util.Scanner;
public class MarksFile {
public static void main(String[] args) throws IOException {
try (PrintWriter pw = new PrintWriter(new FileWriter("marks.txt"))) { // overwrite
pw.println("Anu 78");
pw.println("Biju 91");
}
try (FileWriter fw = new FileWriter("marks.txt", true)) { // append mode
fw.write("Chitra 85" + System.lineSeparator());
}
int total = 0, count = 0;
try (BufferedReader br = new BufferedReader(new FileReader("marks.txt"))) {
String line;
while ((line = br.readLine()) != null) { // null signals the end
String[] parts = line.split(" ");
total += Integer.parseInt(parts[1]);
count++;
}
}
System.out.println(count + " students, average " + (double) total / count);
try (Scanner sc = new Scanner(new File("marks.txt"))) {
sc.next(); // skip "Anu"
System.out.println("first mark = " + sc.nextInt());
}
}
}Java file operations throw the checked IOException; opening a missing file for reading throws its subclass FileNotFoundException. The method must either catch them or declare throws IOException, and try-with-resources closes every stream even when an exception occurs. read() returns an int so that −1 can signal the end of data distinctly from every valid byte (0–255) or character (0–65535).
java.nio.file (Java 7) makes common jobs one-liners: Files.readAllLines(Path.of("marks.txt")) returns a List<String>, Files.write(path, lines) writes them, Files.copy(src, dst) copies, and Files.lines(path) streams lines lazily. (Path.of is Java 11; use Paths.get in Java 7–10.) Since Java 18 the default character set for FileReader and FileWriter is UTF-8 on every platform.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
if (argc != 3) { cerr << "usage: copy <source> <target>\n"; return 1; }
ifstream src(argv[1], ios::in | ios::binary);
if (!src) { cerr << "cannot open " << argv[1] << "\n"; return 1; }
ofstream dst(argv[2], ios::out | ios::binary | ios::trunc);
if (!dst) { cerr << "cannot create " << argv[2] << "\n"; return 1; }
char ch;
long count = 0;
while (src.get(ch)) { // read one byte (binary mode: nothing is translated)
dst.put(ch); // write it out
count++;
}
cout << count << " bytes copied\n";
return 0; // destructors close both files
}import java.io.*;
public class CopyFile {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("usage: java CopyFile <source> <target>");
return;
}
long total = 0;
try (FileInputStream in = new FileInputStream(args[0]);
FileOutputStream out = new FileOutputStream(args[1])) {
byte[] buf = new byte[4096];
int n;
while ((n = in.read(buf)) != -1) { // n = bytes actually read; -1 at the end
out.write(buf, 0, n); // write only the n bytes received
total += n;
}
System.out.println(total + " bytes copied");
} catch (FileNotFoundException e) {
System.out.println("cannot open: " + e.getMessage());
} catch (IOException e) {
System.out.println("copy failed: " + e.getMessage());
}
}
}
// Java 7+ one-liner:
// Files.copy(Paths.get(src), Paths.get(dst), StandardCopyOption.REPLACE_EXISTING);Try the problem first, then reveal the working one step at a time.
notes.txt holds three lines: "Kerala PSC", "Systems Manager exam" and "100 MCQs", each ending with a newline. What does the get()-based counter of Section 4 print, and why must it use get() rather than >>?
The squares 1, 4, 9, 16, 25 are written as 4-byte ints to nums.dat. Find the file size, the value read after seekg(2 * sizeof(int), ios::beg), the get position after that read, and the value read after seekg(−4, ios::end).
marks.txt contains 70, 85 and 90 on separate lines and ends with a newline. Trace while (!a.eof()) { a >> x; sum += x; n++; }.
In the MarksFile program of Section 7, the file gets "Anu 78" and "Biju 91" (PrintWriter) and then "Chitra 85" (FileWriter in append mode). What is printed?
Choose the C++ mode (and the Java equivalent) for: (a) adding lines to an existing log without erasing it; (b) creating a fresh report on every run; (c) updating one record in the middle of a binary file; (d) opening an existing file positioned at the end but able to move back.
A binary file holds 12 records of 28 bytes each. What does tellg() return after seekg(0, ios::end)? At which byte offset does the 5th record start? How would a program compute the record count?
Java: what does each return at the end of the data — FileInputStream.read(), FileReader.read(), BufferedReader.readLine(), Scanner.hasNext()? Why does read() return int instead of byte?
Write a C++ program that appends the line "done" to log.txt (which already contains "start" and a newline) and then prints the file's size in bytes.
Write a Java program that counts the vowels in a text file named on the command line, using FileReader's read() method.
ios::ate only starts at the end (you may seek back and overwrite); ios::app forces every write to the end.ofstream truncates an existing file by default; fstream with in | out does not truncate — and fails if the file does not exist.eof() becomes true only after a read attempt fails, so while (!in.eof()) processes the last value twice; test the read itself instead.new FileWriter(name) overwrites; only new FileWriter(name, true) appends.read() returns an int (−1 at the end); readLine() returns null at the end — not an empty string and not −1.std::string or pointer members with write() stores addresses, not the text — such a file is garbage when read back.10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.