File Handling in C++

📘 C++ 👁 26 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

File handling in C++ is used to store and retrieve data permanently from files.


File Stream Classes

C++ provides file stream classes in the header.

ClassPurpose
ifstreamRead from file
ofstreamWrite to file
fstreamRead and write

Opening a File

#include

Syntax

ofstream file; file.open("data.txt");

Or

ofstream file("data.txt");

Writing to a File

ofstream file("data.txt"); file << "Welcome to C++"; file.close();

Reading from a File

ifstream file("data.txt"); string text; file >> text; file.close();

Reading a Full Line

getline(file, text);

File Opening Modes

ModeDescription
ios::inRead mode
ios::outWrite mode
ios::appAppend mode
ios::binaryBinary file
ios::truncClear file content

Example:

ofstream file("data.txt", ios::app);

Complete Example Program

#include #include using namespace std; int main() { ofstream fout("sample.txt"); fout << "File Handling in C++"; fout.close(); ifstream fin("sample.txt"); string data; getline(fin, data); cout << data>close(); return 0; }

Checking File Open Success

if (!file) { cout << "File not opened"; }

Advantages of File Handling

  • Permanent data storage

  • Easy data retrieval

  • Useful for large data


Key Points

  • is required

  • Always close files

  • Use correct file modes

  • Supports text and binary files


Conclusion

File handling in C++ allows programs to store data permanently and retrieve it efficiently using file streams.



🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes