C++ Files

C++ Tutorial

📁 C++ Files (File Handling)

File handling in C++ allows you to read from and write to files stored on disk.
It is commonly used for data storage, logs, reports, configuration files, etc.

C++ file handling is done using the <fstream> library.


🔹 1. Header Files for File Handling

#include <fstream>

Key classes:

  • ifstream → input file stream (read)

  • ofstream → output file stream (write)

  • fstream → both read and write


🔹 2. Writing to a File (ofstream)

Example: Write Text to a File


 

✔ Creates file if it doesn’t exist
✔ Overwrites file if it exists


🔹 3. Reading from a File (ifstream)

Example: Read Entire File


 


🔹 4. Reading Word by Word


 


🔹 5. Using fstream (Read + Write)


 


🔹 6. File Open Modes

Mode Meaning
ios::in Read
ios::out Write
ios::app Append
ios::trunc Clear file before write
ios::binary Binary file

Example:


 


🔹 7. Append Data to a File



 

✔ Old data preserved


🔹 8. Check If File Opened Successfully


 


🔹 9. Write and Read Numbers


 


🔹 10. Binary File Handling

Write Binary File



 

Read Binary File



 


❌ Common Mistakes

ofstream file;
file << "Hello"; // ❌ file not opened

✔ Correct:

file.open("test.txt");

🔁 File Handling vs Console I/O

File I/O Console I/O
Permanent storage Temporary
Uses <fstream> Uses <iostream>
Slower Faster

📌 Summary

  • File handling uses <fstream>

  • ofstream → write

  • ifstream → read

  • fstream → read & write

  • Always close() files

  • Supports text and binary files

You may also like...