Skip to main content

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.

L1

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 << / >> / getline ideas on file streams.
  • **Real-life:** saving exam marks to marks.txt, loading a config, writing a bill/invoice, logging errors.
ConceptMeaningReal-life
FileNamed storage on diskstudents.txt, log.csv
StreamFlow of bytes in/outPipe between program and file
OpenConnect stream to a fileOpen a notebook to write
CloseFlush & release the fileClose the notebook

File stream classes

  • Include (and usually , ).
  • Prefer checking success with is_open() or if (!stream).
ClassHeaderPurposeTypical use
ofstreamOutput file stream (write)Create/overwrite reports
ifstreamInput file stream (read)Load saved data
fstreamRead and writeUpdate a record file
cin / coutConsole streamsKeyboard / 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 / operationWhat it doesExample
open(filename)Open a file (or use ctor)out.open("a.txt");
open(filename, mode)Open with mode flagsin.open("a.txt", ios::in);
is_open()True if file opened OKif (in.is_open())
close()Close the fileout.close();
operator<<Write formatted dataout << x << "\n";
operator>>Read whitespace-separatedin >> n;
getline(stream, str)Read one line (keeps spaces)getline(in, line);
get()Read one characterchar c = in.get();
put(ch)Write one characterout.put('A');
eof()True if end-of-file hitwhile (!in.eof()) (prefer while(getline))
good() / fail() / bad()Stream state checksif (in.fail())
clear()Clear error flagsin.clear();
read(buf, n)Binary: read n bytesin.read(buf, n);
write(buf, n)Binary: write n bytesout.write(buf, n);
seekg(pos) / seekg(off, dir)Move **get** (read) positionin.seekg(0);
seekp(pos) / seekp(off, dir)Move **put** (write) positionout.seekp(0, ios::end);
tellg()Current read positionauto p = in.tellg();
tellp()Current write positionauto p = out.tellp();
ignore(n, delim)Skip charactersin.ignore(100, '\n');
peek()Look at next char without takingchar c = in.peek();

File open modes

  • Combine flags with | — example: ios::out | ios::app.
  • Default ofstream typically truncates (overwrites) an existing file unless you use app.
ModeMeaningTypical use
ios::inOpen for readingifstream
ios::outOpen for writingofstream
ios::appAppend at endAdd log lines
ios::ateStart at end (can seek)Write near end
ios::truncDelete old contentFresh overwrite
ios::binaryBinary modeImages, structs as bytes
ios::in | ios::outRead + writefstream 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 <<, then close() (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 with ios::binary) — images, exact struct dumps (careful with portability).
PointText fileBinary file
ContentsReadable charactersRaw bytes
Open flagDefaultios::binary
I/O helpers<< >> getlineread / write
Examples.txt, .csv, .log.dat, images, custom blobs
PortabilityEasier across systemsLayout/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.
NeedUseExample
Create / overwrite textofstream + <<Write report
Append log linesofstream + ios::appActivity log
Read lines with spacesifstream + getlineParagraph file
Read numbers/tokensifstream + >>Space-separated data
Update mid-filefstream + seekRecord update (advanced)
Raw bytesbinary + read/writeCustom binary format
Filenames at runtimeargvCLI tools
L2

Advanced — File Handling & Command Line

Seek and tell — random access

  • seekg moves the **read** pointer; seekp moves the **write** pointer.
  • Directions: ios::beg, ios::cur, ios::end.
  • tellg / tellp report 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 with clear() and recover (e.g. ignore).
  • RAII: stream destructor closes the file — still call close() when you want an early flush.
CheckMeaning
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: getline each line, then parse with stringstream splitting on commas.
  • **Real-life:** convert marks.csv into 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.txt key=value lines at startup.
  • CLI tool: converter in.txt out.txt via argv.
  • Backup: copy user notes from one path to another.
L3

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.

L4

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;
}
L5

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.
L6

Practice Programs List

  1. Create notes.txt and write 5 lines; read them back with getline.
  2. Append three timestamp-like messages to app.log using ios::app.
  3. Count lines and words in a user-provided text file.
  4. Write student name and marks to CSV; read and print averages.
  5. Copy input.txt to output.txt; verify contents match.
  6. Read integers from a file and print min, max, sum.
  7. Open a missing file and print a clear error using is_open().
  8. Use seekg/tellg to print an approximate file size.
  9. Build a CLI: program.exe prints the file (use argv).
  10. Parse CSV lines with stringstream and commas.
  11. Write a character-by-character copy using get/put.
  12. Compare text vs binary open for the same small file (observe behavior).
  13. Make a table of 10 file functions from memory, then check against the lesson.
  14. Write a simple inventory: append item lines; later list all items.