πŸ“‚ C++ File Handling
Estimated reading: 4 minutes 275 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 :
Share

C++ Reading and Writing Files

Or Copy Link

CONTENTS
Scroll to Top