π C++ File I/O: Your Digital Filing Cabinet
The Story Beginsβ¦
Imagine you have a magical filing cabinet in your room. You can:
- π Open a drawer (open a file)
- βοΈ Write notes and put them inside (write to file)
- π Read notes you saved before (read from file)
- π Close the drawer when done (close file)
Thatβs exactly what File I/O does in C++! βI/Oβ means Input/Output β getting stuff IN and putting stuff OUT of files.
π What Are File Streams?
Think of a stream like a water pipe. Water flows through pipes, and data flows through streams!
graph TD A["Your Program"] -->|Write Stream| B["File on Disk"] B -->|Read Stream| A
The Three Magic Streams
| Stream | What It Does | Like⦠|
|---|---|---|
ifstream |
Input File stream | Reading a book π |
ofstream |
Output File stream | Writing in a diary βοΈ |
fstream |
Both read AND write | A notebook you use both ways π |
Your First File Stream
#include <fstream>
using namespace std;
// Create a stream to WRITE
ofstream myWriter("diary.txt");
// Create a stream to READ
ifstream myReader("diary.txt");
// Create a stream for BOTH
fstream myNotebook("notes.txt");
Remember: Always include <fstream> β itβs your key to the filing cabinet!
πͺ File Opening Modes
When you open a drawer, you decide what you want to do. Same with files!
The Mode Menu
| Mode | What It Means | Real Life Example |
|---|---|---|
ios::in |
Read only | Looking at photos π· |
ios::out |
Write (erases old stuff!) | Fresh new page π |
ios::app |
Append (add at end) | Adding to a list π |
ios::binary |
Binary mode | Computer language π€ |
ios::trunc |
Erase everything first | Clearing the board π§Ή |
ios::ate |
Start at the end | Jump to last page π |
Combining Modes
You can mix modes like mixing colors!
// Read AND write at same time
fstream file;
file.open("game.dat",
ios::in | ios::out);
// Write in binary, erase old
ofstream save;
save.open("save.bin",
ios::out | ios::binary);
// Add to end without erasing
ofstream log;
log.open("log.txt", ios::app);
The | symbol means βAND this mode too!β
βοΈ Reading and Writing Files
Writing to a File (Like Writing a Letter)
#include <fstream>
#include <string>
using namespace std;
int main() {
// Open our diary
ofstream diary("diary.txt");
// Write some lines
diary << "Dear Diary," << endl;
diary << "Today I learned C++!";
diary << endl;
// Close when done
diary.close();
return 0;
}
<< sends data TO the file (think: pointing toward file)
Reading from a File (Like Reading a Letter)
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ifstream diary("diary.txt");
string line;
// Read line by line
while(getline(diary, line)) {
cout << line << endl;
}
diary.close();
return 0;
}
>> gets data FROM the file (think: pointing away from file)
Reading Word by Word
ifstream book("story.txt");
string word;
while(book >> word) {
cout << word << " ";
}
Reading Character by Character
ifstream letter("note.txt");
char ch;
while(letter.get(ch)) {
cout << ch;
}
π€ Binary File I/O
Text files are for humans. Binary files are for computers!
graph TD A["Text File"] -->|"Hello" = 5 letters| B["5 bytes stored"] C["Binary File"] -->|Number 1000| D["4 bytes stored"]
Why Binary?
| Text | Binary |
|---|---|
| Humans can read it | Only computers understand |
| Bigger file size | Smaller file size |
| Slower | Faster |
| Like: diary.txt | Like: game_save.dat |
Writing Binary Data
#include <fstream>
using namespace std;
int main() {
ofstream file("data.bin",
ios::binary);
int score = 9500;
// write() needs address & size
file.write(
(char*)&score,
sizeof(score)
);
file.close();
return 0;
}
(char*)&score = βtreat this number like raw bytesβ
sizeof(score) = βhow many bytes is this?β
Reading Binary Data
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream file("data.bin",
ios::binary);
int score;
file.read(
(char*)&score,
sizeof(score)
);
cout << "Score: " << score;
file.close();
return 0;
}
Saving a Whole Object
struct Player {
char name[20];
int level;
int coins;
};
Player hero = {"Alex", 10, 500};
// Save the hero!
ofstream save("hero.bin",
ios::binary);
save.write(
(char*)&hero,
sizeof(hero)
);
save.close();
β οΈ Stream Error Handling
What if something goes wrong? Like opening a drawer that doesnβt exist?
The Error Detective Tools
| Method | What It Checks | Example |
|---|---|---|
is_open() |
Did file open OK? | Drawer exists? |
good() |
Everything fine? | All good? β |
eof() |
Reached the end? | Last page? π |
fail() |
Operation failed? | Oops! β |
bad() |
Serious error? | Very bad! π₯ |
Always Check If File Opened!
ifstream file("secret.txt");
if(!file.is_open()) {
cout << "Cannot open file!";
return 1; // Exit with error
}
// Safe to use file now!
The Smart Way: Check Everything
ifstream file("data.txt");
if(!file) {
cout << "Error opening file!";
return 1;
}
int number;
while(file >> number) {
cout << number << endl;
}
if(file.eof()) {
cout << "Finished reading!";
} else if(file.fail()) {
cout << "Read error occurred!";
}
file.close();
Clearing Errors
Sometimes you want to try again after an error:
file.clear(); // Reset error flags
file.seekg(0); // Go back to start
The Complete Safe Pattern
#include <fstream>
#include <iostream>
using namespace std;
int main() {
// Try to open
ifstream file("game.txt");
// Check if opened
if(!file.is_open()) {
cerr << "File not found!";
return 1;
}
string line;
// Read with error checking
while(getline(file, line)) {
if(file.bad()) {
cerr << "Read error!";
break;
}
cout << line << endl;
}
// Always close
file.close();
return 0;
}
π― Quick Summary
graph TD A["File I/O"] --> B["ifstream: Read"] A --> C["ofstream: Write"] A --> D["fstream: Both"] B --> E["Text: getline, >>"] B --> F["Binary: read"] C --> G["Text: <<"] C --> H["Binary: write"] A --> I["Error Checks"] I --> J["is_open, good"] I --> K["eof, fail, bad"]
The Golden Rules
- π¦ Include
<fstream>β Your key to files - πͺ Check
is_open()β Did the door open? - π Always
close()β Close when done! - β οΈ Handle errors β Things can go wrong!
- π€ Use binary β For numbers and objects
π You Did It!
You just learned how to:
- β Open and close files
- β Read and write text
- β Save data in binary
- β Handle errors like a pro
Your programs can now remember things even after they stop running. Thatβs the magic of File I/O!
Think of it this way: Without files, your program is like a goldfish β it forgets everything! With files, itβs like an elephant β it never forgets! π
