π What are File Streams in C++?
In C++, file input and output are handled through the library using an object-oriented stream architecture. Just as std::cout and std::cin interact with console streams, file streams represent connections between your application and files stored on disk. The three core classesβofstream (Output File Stream for writing), ifstream (Input File Stream for reading), and fstream (Bi-directional File Stream for both reading and writing)βinherit from standard stream classes, providing robust, type-safe, and RAII-compliant file management.
std::ofstream opens files for output operations. By default, opening a file for output truncates its existing contents (deletes old data). You can combine open modes like std::ios::app to append data instead.
#include
#include
int main() {
// Open file for writing (creates file if it doesn't exist)
std::ofstream outFile("system_log.txt");
if (!outFile.is_open()) {
std::cerr << "Error: Failed to open file for writing!\n";
return 1;
}
// Write formatted text to file
outFile << "=== ENTERPRISE SYSTEM AUDIT LOG ===\n";
outFile << "Timestamp: 2026-11-12 11:15:00 UTC\n";
outFile << "Status: Operational (Code 200)\n";
// File stream automatically closes when outFile goes out of scope (RAII)
outFile.close();
std::cout << "Data successfully written to system_log.txt\n";
return 0;
}
std::ifstream opens files for input operations. You can read data word-by-word using the extraction operator (>>) or line-by-line using std::getline().
#include
#include
#include
int main() {
std::ifstream inFile("system_log.txt");
if (!inFile.is_open()) {
std::cerr << "Error: File not found or failed to open!\n";
return 1;
}
std::string line;
std::cout << "Reading file contents line by line:\n";
// Read file line-by-line until EOF (End-Of-File)
while (std::getline(inFile, line)) {
std::cout << " > " << line << "\n";
}
inFile.close();
return 0;
}
|).
#include
#include
int main() {
// Open file in APPEND mode so existing logs are not overwritten
std::ofstream outFile("system_log.txt", std::ios::out | std::ios::app);
if (outFile.is_open()) {
outFile << "New Event: User login successful from IP 192.168.1.10\n";
outFile.close();
std::cout << "Log entry appended successfully.\n";
}
return 0;
}
#include
#include
#include
#include
#include
int main() {
std::cout << "============================================\n";
std::cout << "π CSV TRANSACTION LOGGER & PARSER DEMO\n";
std::cout << "============================================\n";
// 1. Write transactional data to transactions.csv
{
std::ofstream csvOut("transactions.csv");
csvOut << "ID,Item,Price\n";
csvOut << "101,Laptop,1200.50\n";
csvOut << "102,Mouse,45.99\n";
csvOut << "103,Keyboard,89.99\n";
} // File closes automatically here
// 2. Read and parse transactions.csv
std::ifstream csvIn("transactions.csv");
std::string line;
double totalRevenue = 0.0;
// Skip header line
std::getline(csvIn, line);
while (std::getline(csvIn, line)) {
std::stringstream ss(line);
std::string id, item, priceStr;
std::getline(ss, id, ',');
std::getline(ss, item, ',');
std::getline(ss, priceStr, ',');
double price = std::stod(priceStr);
totalRevenue += price;
std::cout << "Parsed Item: " << item << " | Price: $" << price << "\n";
}
std::cout << "--------------------------------------------\n";
std::cout << "Total Computed Revenue: $" << totalRevenue << "\n";
std::cout << "============================================\n";
return 0;
}
C++ FILE I/O ARCHITECTURE REFERENCE:
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Stream Class β Default Open Mode β Purpose & Operational Behavior β
βββββββββββββββββββββββΌββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β `std::ofstream` β `std::ios::out | trunc` β Writing output to files (erases existing file contents). β
β `std::ifstream` β `std::ios::in` β Reading input from existing files. β
β `std::fstream` β `std::ios::in | out` β Bi-directional reading and writing. β
βββββββββββββββββββββββ΄ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β OPEN MODE FLAGS: β
β * `std::ios::app` β Appends all output to the end of file without overwriting. β
β * `std::ios::binary`β Opens file in binary mode (disables text newline conversions like `\n` to `\r\n`). β
β * `std::ios::ate` β Positions file read/write pointer at the end of file immediately upon opening. β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β ENGINEERING BEST PRACTICES: β
β 1. Always check if a file opened successfully using `if (!file.is_open())` before attempting read/write operations.β
β 2. Rely on RAII file closing by letting stream objects go out of scope, or call `.close()` explicitly. β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ