File I-O

Back

Loading concept...

πŸ“ 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, &gt;&gt;"] B --> F["Binary: read"] C --> G["Text: &lt;&lt;"] C --> H["Binary: write"] A --> I["Error Checks"] I --> J["is_open, good"] I --> K["eof, fail, bad"]

The Golden Rules

  1. πŸ“¦ Include <fstream> – Your key to files
  2. πŸšͺ Check is_open() – Did the door open?
  3. πŸ”’ Always close() – Close when done!
  4. ⚠️ Handle errors – Things can go wrong!
  5. πŸ€– 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! 🐘

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.