πŸ“‚ C++ File Handling
Estimated reading: 3 minutes 41 views

πŸ“„ C++ File Streams – <fstream> for Reading and Writing Files


🧲 Introduction – Why File Streams Are Essential in C++

In C++, file streams provide an object-oriented way to read and write data to files using the same syntax as cin and cout. The <fstream> header defines specialized classesβ€”ifstream, ofstream, and fstreamβ€”to handle file input/output operations easily and efficiently.

🎯 In this guide, you’ll learn:

  • What file stream classes are and how they work
  • How to open, read, write, and close files
  • Syntax and examples of reading/writing with streams
  • File open modes and best practices

πŸ” What Is <fstream>?

<fstream> is a C++ standard library header that includes the classes needed to handle file operations:

ClassPurposeInherits From
ifstreamInput stream for readingistream
ofstreamOutput stream for writingostream
fstreamInput/output streamiostream

πŸ’» Code Examples – Reading & Writing

βœ… Writing to a File Using ofstream

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

int main() {
    ofstream outFile("sample.txt");
    outFile << "Hello, File Streams!" << endl;
    outFile.close();
    return 0;
}

βœ… Reading from a File Using ifstream

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

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

βœ… Using fstream for Both Reading and Writing

#include <fstream>
using namespace std;

int main() {
    fstream file("data.txt", ios::in | ios::out | ios::trunc);
    file << "Line 1\n";
    file.seekg(0);
    string line;
    getline(file, line);
    cout << line << endl;
    file.close();
    return 0;
}

βš™οΈ File Opening Modes

File streams can be combined with mode flags:

ModeDescription
ios::inOpen for reading
ios::outOpen for writing
ios::appAppend to end of file
ios::truncTruncate existing file (default for ofstream)
ios::binaryOpen file in binary mode

πŸ” File Handling Functions

FunctionPurpose
.open()Opens a file
.close()Closes the file
.is_open()Returns true if file successfully opened
.eof()Checks for end-of-file
.fail()Checks for failure in file operation

πŸ’‘ Best Practices & Tips

πŸ“˜ Always check .is_open() before reading/writing
πŸ’‘ Use ofstream with ios::app to preserve existing data
⚠️ Remember to .close() files to avoid resource leaks
πŸ“¦ Use relative paths to improve cross-platform portability


πŸ“Œ Summary – Recap & Next Steps

πŸ” Key Takeaways:

  • Use ifstream, ofstream, and fstream from <fstream> to handle files
  • Support text and binary data with different open modes
  • Streams behave similarly to cin and cout, making them easy to use

βš™οΈ Real-World Relevance:
C++ file streams are used in logging systems, report generation, configuration loading, and all forms of persistent data handling.

βœ… Next Steps:
Learn how to read and write content using file streams with more advanced techniques and handle files in binary mode.


❓FAQ – C++ File Streams

❓ What’s the difference between ofstream and fstream?
ofstream is for writing only, while fstream supports both reading and writing.

❓ Do I need to manually close the file?
βœ… Yes, always call .close() after you’re done to release resources.

❓ What if I open a file that doesn’t exist?
ifstream will fail to open it; ofstream will create it by default.

❓ Can I check if a file opened successfully?
βœ… Yes. Use .is_open() to verify.

❓ How do I avoid overwriting an existing file?
Use ios::app mode or check for file existence before writing.


Share Now :

Leave a Reply

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

Share

C++ File Streams – <fstream>

Or Copy Link

CONTENTS
Scroll to Top