How to Use fstream in C++ for File Input and Output
In C++, use the
fstream library to read from and write to files by creating an fstream object. Open a file with modes like ios::in for reading or ios::out for writing, then use stream operators to handle file data.Syntax
The fstream class is used to handle file input and output. You create an fstream object and open a file with a mode:
ios::infor readingios::outfor writingios::appto append dataios::binaryfor binary files
Example syntax:
std::fstream file("filename.txt", std::ios::in | std::ios::out);This opens the file for both reading and writing.
cpp
std::fstream file("filename.txt", std::ios::in | std::ios::out);Example
This example shows how to write text to a file and then read it back using fstream.
cpp
#include <iostream> #include <fstream> #include <string> int main() { std::fstream file("example.txt", std::ios::out); // Open for writing if (!file) { std::cerr << "Error opening file for writing." << std::endl; return 1; } file << "Hello, fstream!" << std::endl; file.close(); file.open("example.txt", std::ios::in); // Open for reading if (!file) { std::cerr << "Error opening file for reading." << std::endl; return 1; } std::string line; while (std::getline(file, line)) { std::cout << line << std::endl; } file.close(); return 0; }
Output
Hello, fstream!
Common Pitfalls
Common mistakes when using fstream include:
- Not checking if the file opened successfully before reading or writing.
- Forgetting to close the file, which can cause data loss.
- Using the wrong mode (e.g., opening with
ios::inonly when you want to write). - Not resetting the file pointer when switching between reading and writing.
Always check the file state and close files properly.
cpp
#include <fstream> #include <iostream> int main() { std::fstream file; file.open("data.txt", std::ios::in); // Open for reading only // Wrong: Trying to write to a read-only file if (file) { file << "Trying to write"; // This will fail silently or cause error } file.close(); // Correct way: file.open("data.txt", std::ios::out); // Open for writing if (file) { file << "Writing correctly" << std::endl; } file.close(); return 0; }
Quick Reference
Here is a quick summary of common fstream modes:
| Mode | Meaning |
|---|---|
| ios::in | Open file for reading |
| ios::out | Open file for writing (overwrite) |
| ios::app | Open file for appending (write at end) |
| ios::binary | Open file in binary mode |
| ios::trunc | Truncate file to zero length if it exists |
Key Takeaways
Use
fstream with appropriate modes to read and write files in C++.Always check if the file opened successfully before accessing it.
Close files after use to ensure data is saved properly.
Use
ios::in for reading, ios::out for writing, and combine modes as needed.Be careful switching between reading and writing; reset file pointers if necessary.