What is a File?

  • A file is a storage unit on a computer that holds data permanently.

  • Unlike variables, which are stored temporarily in RAM, files are stored on hard disk, SSD, or external storage.

Real-World Analogy:

  • File = Notebook

  • Pages in the notebook = Lines of data

  • You can write, read, and update the notebook anytime

Why files are needed:

  1. Persistence → Data remains after program ends

  2. Large storage → Store more data than memory allows

  3. Sharing → Data can be shared with other programs

File Concepts in C++

Types of Files

TypeDescriptionExample
Text FileStores data as readable text.txt, .csv
Binary FileStores data in binary form.bin, .dat

Text File Example:

 
Name, Age, Grade
Ali,  20,    A
Sara, 19,    B

Binary File Example:

  • Stores actual memory data

  • Not human-readable

  • Faster for computer processing

File Operations in C++

  1. Opening a File → Connect your program to the file

  2. Closing a File → Disconnect the file

  3. Reading from a File → Get data from the file

  4. Writing to a File → Send data to the file

File Streams

C++ provides fstream library to work with files:

Stream ClassPurpose
ofstreamWrite to a file
ifstreamRead from a file
fstreamBoth read and write

Include header:

 
#include <fstream>

#include <iostream>

using namespace std;

Writing to a File

Syntax:

 
ofstream file("example.txt"); // create or open file
file << "Hello World" << endl;
file.close(); // always close file

Full Example 1:

 
#include <fstream>
#include <iostream>

using namespace std;
int main() {
ofstream myFile("data.txt"); // create or open file
if(myFile.is_open()) {
myFile << "Ali, 20, A\n";
myFile << "Sara, 19, B\n";
cout << "Data written successfully!" << endl;
}
myFile.close();
return 0;
}

Practice Exercise:

  • Write a program to store 5 student names and marks in a file students.txt.

Reading from a File

Syntax:

 
ifstream file("example.txt"); // open file to read
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();

Full Example 2:

 
#include <fstream>

#include <iostream>
using namespace std;
int main() {
ifstream myFile("data.txt");
string line;
if(myFile.is_open()) {
while(getline(myFile, line)) {
cout << line << endl;
}
}
myFile.close();
return 0;
}

Practice Exercise:

  • Read the student data from students.txt and display only students with marks > 18.

Opening Modes

ModeSymbolDescription
Outputios::outWrite to file (overwrite)
Inputios::inRead from file
Appendios::appAdd data at the end
Binaryios::binaryOpen file in binary mode
Read & Writeios::inios::out

Example of Append Mode:

 
ofstream file("data.txt", ios::app);
file << "Zara, 21, A\n"; // adds to the file
file.close();

Binary Files (Optional Deep Info)

  • Binary files store raw memory data

  • Faster than text files

  • Used for large datasets, images, programs

Example:

 
#include <fstream>
using namespace std;
int main() {
ofstream outFile("data.bin", ios::binary);
int num = 123;
outFile.write(reinterpret_cast<char*>(&num), sizeof(num));
outFile.close();
return 0;
}

Explanation:

  • reinterpret_cast<char*> converts memory address to char pointer

  • sizeof(num) ensures correct number of bytes

Advantages of Using Files

  1. Data persists after program ends

  2. Large storage → no memory limitation

  3. Data sharing between programs

  4. Logging and record keeping

Limitations of Files

  1. Slower than memory operations → accessing hard disk takes time

  2. File corruption risk → if program crashes while writing

  3. Complex management → need to open, close, check errors

  4. Not real-time → cannot instantly update like variables

Real-World Analogies

ConceptFile Analogy
FileNotebook
WritingPen writing on notebook
ReadingReading notebook
AppendAdding more pages at the end
Binary FileSecret encrypted notebook, readable only by program

Extra Practice Exercises

  1. Write Student Info:

    • Create students.txt

    • Store name, age, and grade for 5 students

  2. Read & Filter:

    • Read students.txt

    • Display students with grade ‘A’ only

  3. Append Data:

    • Add new student info without overwriting old data

  4. Binary Data Storage:

    • Store an integer array into numbers.bin

    • Read it back and display