Stream I/O in C++
What is Stream I/O?
Stream I/O: Mechanism for reading and writing data to/from files or consoles.
A stream is an abstraction used to perform I/O operations (input/output).
Types of Streams
Input Stream (std::cin): For reading input from the user or files.
Output Stream (std::cout): For writing output to the screen or files.
File Streams (std::ifstream, std::ofstream): For file input and output.
Basic Input and Output
std::cin: Reads input from the console.
std::cout: Prints output to the console.
#include <iostream>
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num; // Input
std::cout << "You entered: " << num << std::endl; // Output
return 0;
}
File Input and Output
std::ifstream: Used to read from files.
std::ofstream: Used to write to files.
#include <fstream>
#include <iostream>
int main() {
std::ofstream outFile("example.txt"); // Create and open file
outFile << "Hello, file!" << std::endl; // Write to file
outFile.close(); // Close file
std::ifstream inFile("example.txt"); // Open file for reading
std::string content;
inFile >> content; // Read from file
std::cout << "File content: " << content << std::endl;
inFile.close();
return 0;
}
Stream States
Streams can be in different states: good, fail, eof, bad.
Use std::cin.fail() to check for errors.
int num;
std::cin >> num;
if (std::cin.fail()) {
std::cout << "Input error!" << std::endl;
}
File Opening Modes
std::ios::in: Open for reading.
std::ios::out: Open for writing.
std::ios::app: Append to file.
std::ios::binary: Open in binary mode.
std::ofstream outFile("data.txt", std::ios::app);
outFile << "Adding to file" << std::endl;
outFile.close();
Checking File Open Status
Use is_open() to check if a file is successfully opened.
std::ifstream inFile("data.txt");
if (inFile.is_open()) {
std::cout << "File opened successfully!" << std::endl;
} else {
std::cout << "Failed to open file!" << std::endl;
}
Error Handling in Stream I/O
Handle errors by checking stream states after operations.
Use clear() to reset stream state.
std::ifstream inFile("nonexistent.txt");
if (!inFile) { // Check if file is open
std::cout << "Error opening file!" << std::endl;
inFile.clear(); // Clear error state
}
Store a C++ Object in a File
To store an object in a file in C++, you typically use the ofstream class for output and serialize
the object—that is, write its data members to the file in a structured way.
C++ doesn't have built-in object serialization like some other languages (e.g. Python or Java), so
you need to manually define how to save and load the object.
#include <iostream>
#include <fstream>
#include <string>
class Person {
public:
std::string name;
int age;
// Serialize: Save object to file
void saveToFile(std::ofstream &out) const {
out << name << "\n" << age << "\n";
}
// Deserialize: Load object from file
void loadFromFile(std::ifstream &in) {
std::getline(in, name);
in >> age;
in.ignore(); // clear newline after reading int
}
};
int main() {
// Create object
Person p1;
p1.name = "Alice";
p1.age = 30;
// Save object to file
std::ofstream outFile("person.txt");
if (outFile.is_open()) {
p1.saveToFile(outFile);
outFile.close();
}
// Load object from file
Person p2;
std::ifstream inFile("person.txt");
if (inFile.is_open()) {
p2.loadFromFile(inFile);
inFile.close();
}
// Output loaded data
std::cout << "Name: " << p2.name << ", Age: " << p2.age << std::endl;
return 0;
}
This example stores data as plain text.
saveToFile and loadFromFile are manual serialization/deserialization methods.
For more advanced use (like storing binary data), you can use ofstream in binary mode
(std::ios::binary).
Summary
Streams: Abstractions for I/O operations in C++.
Input/Output: std::cin, std::cout for console I/O, std::ifstream, std::ofstream for file I/O.
Error handling: Check stream states for successful operations and errors.