๐Ÿ“‚ C++ File Handling
Estimated reading: 4 minutes 19 views

โœ๏ธ C++ Reading and Writing Files โ€“ Text and Binary I/O Made Simple


๐Ÿงฒ Introduction โ€“ Why File I/O Is Crucial in C++

C++ provides powerful tools for performing file input and output (I/O), allowing programs to persist data between executions. Whether you’re building a text editor, logger, or a binary data processor, understanding how to read from and write to files is essential.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to read and write text files
  • How to perform binary file I/O
  • Stream-based I/O using ifstream, ofstream, and fstream
  • Best practices for efficient and safe file handling

๐Ÿ“˜ Text File I/O โ€“ Line and Word-Based Operations

โœ… Writing to a Text File

#include <fstream>
using namespace std;

int main() {
    ofstream out("data.txt");
    out << "Name: John" << endl;
    out << "Age: 25" << endl;
    out.close();
    return 0;
}

โœ… Reading from a Text File (Line-by-Line)

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() {
    ifstream in("data.txt");
    string line;
    while (getline(in, line)) {
        cout << line << endl;
    }
    in.close();
    return 0;
}

โœ… Reading Word-by-Word

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() {
    ifstream file("data.txt");
    string word;
    while (file >> word) {
        cout << word << endl;
    }
    file.close();
    return 0;
}

๐Ÿ’พ Binary File I/O โ€“ Byte-Level Reading & Writing

Binary mode preserves the raw byte structure of data, ideal for writing objects or non-text files.

โœ… Writing Binary Data

#include <fstream>
using namespace std;

struct Record {
    int id;
    float score;
};

int main() {
    Record r = {1, 95.5f};
    ofstream out("record.bin", ios::binary);
    out.write((char*)&r, sizeof(r));
    out.close();
    return 0;
}

โœ… Reading Binary Data

#include <fstream>
#include <iostream>
using namespace std;

struct Record {
    int id;
    float score;
};

int main() {
    Record r;
    ifstream in("record.bin", ios::binary);
    in.read((char*)&r, sizeof(r));
    cout << "ID: " << r.id << ", Score: " << r.score << endl;
    in.close();
    return 0;
}

๐Ÿ“‚ Common File I/O Functions

FunctionPurpose
.open()Opens a file
.close()Closes the file
.is_open()Checks if file is successfully opened
.eof()Detects end of file
getline()Reads a line into a string
>> and <<Stream insertion and extraction

๐Ÿงช File Stream Modes Recap

ModeDescription
ios::inRead mode
ios::outWrite mode
ios::appAppend to file
ios::binaryBinary file mode
ios::truncTruncate file if it exists

๐Ÿ’ก Best Practices & Tips

๐Ÿ“˜ Always check .is_open() before operating on a file
๐Ÿ“ฆ Use ios::app to avoid overwriting content when appending
โš ๏ธ Don’t forget to .close() files to free resources
๐Ÿ’ก Use binary I/O for speed and compact data formats


๐Ÿ› ๏ธ Use Cases for Reading and Writing Files

๐Ÿ“Š Logging Systems โ€“ Write logs, errors, events
๐Ÿงพ Report Generation โ€“ Store user data and system output
๐ŸŽฎ Save Games โ€“ Load and save structured data
๐Ÿ“„ Form-Based Apps โ€“ Read/write formatted user input
๐Ÿ“ File Converters โ€“ Convert between formats using line/byte parsing


๐Ÿ“Œ Summary โ€“ Recap & Next Steps

๐Ÿ” Key Takeaways:

  • C++ supports both text and binary file I/O using file streams
  • Use ifstream, ofstream, and fstream with the appropriate mode flags
  • Use getline() for line input and stream operators (>>, <<) for formatted data

โš™๏ธ Real-World Relevance:
C++ file I/O is widely used in applications like loggers, report writers, data import/export utilities, and configuration-driven tools.

โœ… Next Steps:
Explore C++ File Modes & Binary File Operations to control how files are accessed, opened, and processed.


โ“FAQ โ€“ C++ Reading and Writing Files

โ“ What’s the difference between reading by >> and getline()?
>> stops at whitespace, while getline() reads the full line including spaces.

โ“ Can I write both binary and text to the same file?
โš ๏ธ Not recommendedโ€”use one mode per file to avoid data corruption.

โ“ What happens if I read past EOF?
The stream enters a fail state, and no more data is read.

โ“ How do I overwrite vs append to a file?
Use ios::out for overwrite, and ios::app for append mode.

โ“ Should I always check for .is_open()?
โœ… Yes. It prevents undefined behavior and allows error reporting.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

C++ Reading and Writing Files

Or Copy Link

CONTENTS
Scroll to Top