Memory & Language Features
File Handling & Command Line
Complete lesson for File Handling & Command Line using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with C++ OOP and STL where relevant.
Basics — File Handling & Command Line
Section: Memory & Language Features. C++ file handling — fstream classes, file functions table, open modes, and command-line arguments.
What is file handling?
- **File handling** means reading data from and writing data to files on disk so information survives after the program ends.
- C++ uses **stream classes** from
:ifstream(input),ofstream(output),fstream(both). - Console uses
cin/cout; files use the same<</>>/getlineideas on file streams. - **Real-life:** saving exam marks to
marks.txt, loading a config, writing a bill/invoice, logging errors.
| Concept | Meaning | Real-life |
|---|---|---|
| File | Named storage on disk | students.txt, log.csv |
| Stream | Flow of bytes in/out | Pipe between program and file |
| Open | Connect stream to a file | Open a notebook to write |
| Close | Flush & release the file | Close the notebook |
File stream classes
- Include
(and usually,). - Prefer checking success with
is_open()orif (!stream).
| Class | Header | Purpose | Typical use |
|---|---|---|---|
ofstream | | Output file stream (write) | Create/overwrite reports |
ifstream | | Input file stream (read) | Load saved data |
fstream | | Read and write | Update a record file |
cin / cout | | Console streams | Keyboard / screen |
File functions & operations (table)
- These are the most used **member functions** of file stream objects (
ifstream/ofstream/fstream). - Call them as
file.function(...).
| Function / operation | What it does | Example |
|---|---|---|
open(filename) | Open a file (or use ctor) | out.open("a.txt"); |
open(filename, mode) | Open with mode flags | in.open("a.txt", ios::in); |
is_open() | True if file opened OK | if (in.is_open()) |
close() | Close the file | out.close(); |
operator<< | Write formatted data | out << x << "\n"; |
operator>> | Read whitespace-separated | in >> n; |
getline(stream, str) | Read one line (keeps spaces) | getline(in, line); |
get() | Read one character | char c = in.get(); |
put(ch) | Write one character | out.put('A'); |
eof() | True if end-of-file hit | while (!in.eof()) (prefer while(getline)) |
good() / fail() / bad() | Stream state checks | if (in.fail()) |
clear() | Clear error flags | in.clear(); |
read(buf, n) | Binary: read n bytes | in.read(buf, n); |
write(buf, n) | Binary: write n bytes | out.write(buf, n); |
seekg(pos) / seekg(off, dir) | Move **get** (read) position | in.seekg(0); |
seekp(pos) / seekp(off, dir) | Move **put** (write) position | out.seekp(0, ios::end); |
tellg() | Current read position | auto p = in.tellg(); |
tellp() | Current write position | auto p = out.tellp(); |
ignore(n, delim) | Skip characters | in.ignore(100, '\n'); |
peek() | Look at next char without taking | char c = in.peek(); |
File open modes
- Combine flags with
|— example:ios::out | ios::app. - Default
ofstreamtypically truncates (overwrites) an existing file unless you useapp.
| Mode | Meaning | Typical use |
|---|---|---|
ios::in | Open for reading | ifstream |
ios::out | Open for writing | ofstream |
ios::app | Append at end | Add log lines |
ios::ate | Start at end (can seek) | Write near end |
ios::trunc | Delete old content | Fresh overwrite |
ios::binary | Binary mode | Images, structs as bytes |
ios::in | ios::out | Read + write | fstream update |
#include <fstream>
using namespace std;
int main() {
ofstream log("app.log", ios::app);
log << "Started\n";
log.close();
return 0;
} Writing to a file (ofstream)
- Create
ofstream, write with<<, thenclose()(destructor also closes). - Always verify the file opened — disk full / bad path / permissions can fail.
- **Real-life:** save a customer bill, export a CSV of marks.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream out("data.txt");
if (!out) {
cout << "Cannot create file\n";
return 1;
}
out << "Name,Marks\n";
out << "Asha,90\n";
out << "Ravi,85\n";
out.close();
cout << "Saved data.txt\n";
return 0;
} Reading a file (ifstream)
- Prefer
while (getline(in, line))for line-oriented text. >>stops at whitespace — fine for numbers/tokens, not full sentences.- **Real-life:** load settings, import a student list.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ifstream in("data.txt");
if (!in.is_open()) {
cout << "Cannot open file\n";
return 1;
}
string line;
while (getline(in, line)) {
cout << line << "\n";
}
in.close();
return 0;
} Text files vs binary files
- **Text:** human-readable characters (
<<,>>,getline). - **Binary:** raw bytes (
read/write, open withios::binary) — images, exact struct dumps (careful with portability).
| Point | Text file | Binary file |
|---|---|---|
| Contents | Readable characters | Raw bytes |
| Open flag | Default | ios::binary |
| I/O helpers | << >> getline | read / write |
| Examples | .txt, .csv, .log | .dat, images, custom blobs |
| Portability | Easier across systems | Layout/endian issues possible |
Command-line arguments (argc / argv)
int main(int argc, char* argv[])receives arguments from the shell.argc= count;argv[0]= program name;argv[1]…= user args.- **Real-life:**
./app input.txt output.txt— filenames passed without recompiling.
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
cout << "Args: " << argc << "\n";
for (int i = 0; i < argc; i++) {
cout << i << ": " << argv[i] << "\n";
}
return 0;
} Which API should you use?
- Match the job — keep error checks.
| Need | Use | Example |
|---|---|---|
| Create / overwrite text | ofstream + << | Write report |
| Append log lines | ofstream + ios::app | Activity log |
| Read lines with spaces | ifstream + getline | Paragraph file |
| Read numbers/tokens | ifstream + >> | Space-separated data |
| Update mid-file | fstream + seek | Record update (advanced) |
| Raw bytes | binary + read/write | Custom binary format |
| Filenames at runtime | argv | CLI tools |
Advanced — File Handling & Command Line
Seek and tell — random access
seekgmoves the **read** pointer;seekpmoves the **write** pointer.- Directions:
ios::beg,ios::cur,ios::end. tellg/tellpreport the current position — useful to measure file size.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream in("data.txt", ios::binary);
if (!in) return 1;
in.seekg(0, ios::end);
auto size = in.tellg();
cout << "Size approx = " << size << " bytes\n";
in.seekg(0, ios::beg);
return 0;
} Stream state and error handling
- Failed open, bad path, or bad extraction sets failbit — check after operations.
- After a failed
>>, clear withclear()and recover (e.g.ignore). - RAII: stream destructor closes the file — still call
close()when you want an early flush.
| Check | Meaning |
|---|---|
is_open() | Associated file is open |
good() | No error flags set |
eof() | End of file reached |
fail() | Failed operation (recoverable often) |
bad() | Serious stream error |
Copy file & CSV-style parsing
- Copy: read lines/chars from one stream and write to another.
- CSV:
getlineeach line, then parse withstringstreamsplitting on commas. - **Real-life:** convert
marks.csvinto totals per student.
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ifstream in("data.txt");
string line;
while (getline(in, line)) {
stringstream ss(line);
string name, marks;
if (getline(ss, name, ',') && getline(ss, marks)) {
cout << name << " => " << marks << "\n";
}
}
return 0;
} Binary write/read of a POD struct (careful)
- Possible for simple POD structs; **not** safe for
std::string/ pointers inside. - Prefer portable text/CSV or a defined binary format for real apps.
#include <fstream>
using namespace std;
struct Rec { int id; double value; };
int main() {
Rec r{1, 99.5};
ofstream out("rec.bin", ios::binary);
out.write(reinterpret_cast<char*>(&r), sizeof(r));
out.close();
Rec loaded{};
ifstream in("rec.bin", ios::binary);
in.read(reinterpret_cast<char*>(&loaded), sizeof(loaded));
return 0;
} Real-life file handling models
- School: export attendance CSV daily.
- Shop: append each sale to
sales.log. - App config: read
settings.txtkey=value lines at startup. - CLI tool:
converter in.txt out.txtvia argv. - Backup: copy user notes from one path to another.
Tricky Interview Points
Q1) What is file handling in C++?
Answer Reading from and writing to files using stream classes such as ifstream, ofstream, and fstream from <fstream>.
Q2) Difference between ifstream, ofstream, and fstream?
Answer ifstream is for input (read), ofstream for output (write), fstream supports both reading and writing.
Q3) Name important file functions.
Answer open, close, is_open, get, put, getline (free function), read, write, seekg, seekp, tellg, tellp, eof, clear, and operators << and >>.
Q4) What does ios::app do?
Answer Opens the file in append mode so new output is written at the end without erasing existing content.
Q5) How do you read a full line including spaces?
Answer Use getline(infile, stringVariable); — operator>> stops at whitespace.
Q6) Text file vs binary file?
Answer Text stores human-readable characters; binary stores raw bytes and is usually opened with ios::binary using read/write.
Q7) What are seekg and tellg?
Answer seekg moves the get (read) position; tellg returns the current get position in the file.
Q8) Why check is_open()?
Answer Opening can fail (missing file, permissions, bad path). Checking prevents using an invalid stream.
Q9) What are argc and argv?
Answer Command-line argument count and array of C-strings. argv[0] is the program name; further entries are user-provided arguments.
Q10) Does the file close automatically?
Answer Yes — the stream destructor closes it (RAII). You may still call close() explicitly when finished early.
Q11) What is ios::trunc?
Answer If the file exists, its contents are discarded when opened for output — typical default overwrite behavior for ofstream.
Q12) How do you append to a log file?
Answer Open ofstream with ios::app (optionally ios::out | ios::app) and write new lines.
Simple Programs
Write text with ofstream
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream out("hello.txt");
if (!out) return 1;
out << "Hello File Handling\n";
out.close();
cout << "Written\n";
return 0;
} Read lines with getline
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ifstream in("hello.txt");
string line;
while (getline(in, line)) cout << line << "\n";
return 0;
} Append to a log
#include <fstream>
using namespace std;
int main() {
ofstream log("app.log", ios::app);
log << "Event at end of file\n";
return 0;
} Count lines, words, chars
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
ifstream in("hello.txt");
string line;
int lines = 0, words = 0, chars = 0;
while (getline(in, line)) {
lines++;
chars += static_cast<int>(line.size()) + 1;
stringstream ss(line);
string w;
while (ss >> w) words++;
}
cout << lines << " " << words << " " << chars << "\n";
return 0;
} Copy file
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream in("hello.txt");
ofstream out("hello_copy.txt");
string line;
while (getline(in, line)) out << line << "\n";
return 0;
} Read numbers with >>
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream in("nums.txt"); // e.g. 10 20 30
int x, sum = 0;
while (in >> x) sum += x;
cout << "Sum = " << sum << "\n";
return 0;
} argc/argv echo
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
for (int i = 0; i < argc; i++)
cout << argv[i] << "\n";
return 0;
} Problem Solving Tricks
- Always check open success before reading/writing.
- Use getline for lines with spaces; >> for tokens/numbers.
- Append logs with ios::app so you do not wipe history.
- Close when done — or rely on RAII destructor.
- Prefer while (getline(in, line)) over while (!eof()).
- Combine modes with | : ios::in | ios::binary.
- tellg after seekg(0, ios::end) ≈ file size for binary.
- Keep text simple (CSV) before inventing binary formats.
- Pass filenames via argv for flexible tools.
- After a failed >>, call clear() before continuing.
- Flush important data: out.flush() or close().
- Do not write std::string objects with raw binary write — write their characters instead.
Practice Programs List
- Create notes.txt and write 5 lines; read them back with getline.
- Append three timestamp-like messages to app.log using ios::app.
- Count lines and words in a user-provided text file.
- Write student name and marks to CSV; read and print averages.
- Copy input.txt to output.txt; verify contents match.
- Read integers from a file and print min, max, sum.
- Open a missing file and print a clear error using is_open().
- Use seekg/tellg to print an approximate file size.
- Build a CLI: program.exe
prints the file (use argv). - Parse CSV lines with stringstream and commas.
- Write a character-by-character copy using get/put.
- Compare text vs binary open for the same small file (observe behavior).
- Make a table of 10 file functions from memory, then check against the lesson.
- Write a simple inventory: append item lines; later list all items.