📁 C++ File I/O – Read and Write Files Easily
Want to save your data even after the program ends? That’s where File I/O comes in! 📄
Using <fstream>
, C++ lets you read from and write to files using just a few lines of code. It’s like giving your program memory!
📚 Required Header
#include <fstream>
This header gives you access to three handy file stream classes:
ofstream
– for writing filesifstream
– for reading filesfstream
– for both reading and writing
📝 Example: Writing to a File
#include <iostream> #include <fstream> using namespace std; int main() { ofstream myFile("example.txt"); // Create and open file myFile << "Hello, file world!\n"; // Write to file myFile.close(); // Always close the file return 0; }
📖 Example: Reading from a File
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream myFile("example.txt"); // Open file for reading string line; while (getline(myFile, line)) { cout << line << endl; // Print each line } myFile.close(); return 0; }
⚙️ File Modes
You can open files in different modes using fstream
flags:
ios::in
– Readios::out
– Writeios::app
– Appendios::binary
– Binary mode
🔐 Always Close Files
Use myFile.close()
to avoid memory leaks and ensure data is saved properly.
✅ Summary
- File I/O helps store data even after the program ends.
- Use
ofstream
to write andifstream
to read. - Always close the file when you’re done!