1 Predefined Standard Stream Objects #
In C++, predefined standard stream objects are several global objects provided by the iostream library, representing standard input/output devices (usually the keyboard and screen). These objects are automatically created when the program starts and can be used directly.
| Object | Name | Device | Equivalent to C | Class |
|---|---|---|---|---|
cin |
Standard Input | Keyboard | stdin |
istream |
cout |
Standard Output | Screen | stdout |
ostream |
cerr |
Standard Error | Screen | stderr Unbuffered |
ostream |
clog |
Standard Log | Screen | stderr Buffered |
ostream |
2 File I/O Implementation #
File I/O is defined in the header file <fstream>
- Opening a File:
open()andclose()are the standard procedures for file operations; - The second parameter of the member function
open()specifies the file opening mode, with options including append modeios::app, etc.; - Pointer Positioning:
seekg()seekp()is crucial for random access within a file; <<overloads the stream insertion and left shift operators, and>>overloads the stream extraction and right shift operators;- C++’s stream mechanism supports various media such as files, strings, and arrays, offering diverse I/O capabilities.
| Class | Name | Description |
|---|---|---|
ifstream |
Input file stream | Used to read information from a file |
ofstream |
Output file stream | Used to create a file and write information to it |
fstream |
File stream | Can read and write files simultaneously |
#include <fstream> // File stream operations
#include <iostream> // Standard input/output
using namespace std;
int main() {
char data[100];
// 1. Write to a file
ofstream outfile; // Create an output file stream object
outfile.open("afile.dat"); // Open the file, write mode ios::out
if (!outfile.is_open()) { // Check if the stream object is associated with a file
cerr << "The file 'afile.dat' does not exist" << endl;
return 1;
}
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100); // Read a line from the keyboard, up to 100 characters
outfile << data << endl; // Write the name to the file and add a newline
cout << "Enter your age: ";
cin >> data;
cin.ignore(); // Clear the input buffer, eliminating the influence of the previous input on the next input
outfile << data << endl; // Write the age to the file
outfile.close(); // Close the file, ensuring the data is written to disk
// 2. Read the file
ifstream infile("afile.dat"); // Open the file in read mode
if (!infile.is_open()) {
cerr << "The file 'afile.dat' does not exist" << endl;
return 1;
}
cout << "Reading from the file" << endl;
while (infile >> data) {
cout << data << endl;
}
infile.close();
return 0;
}