1 预定义标准流对象 #
在 C++ 中,预定义标准流对象是 iostream 库提供的几个全局对象,表示标准的输入输出设备(通常是键盘和屏幕)。这些对象在程序启动时自动创建,可以直接使用。
| 对象 | 名称 | 对应设备 | 相当于C语言 | 类 |
|---|---|---|---|---|
cin |
标准输入 | 键盘 | stdin |
istream |
cout |
标准输出 | 屏幕 | stdout |
ostream |
cerr |
标准错误 | 屏幕 | stderr 无缓冲 |
ostream |
clog |
标准日志 | 屏幕 | stderr 有缓冲 |
ostream |
2 文件 I/O 实现 #
文件 I/O 定义于头文件 <fstream>
- 文件的打开
open()与关闭close()是文件操作的标准流程; - 成员函数
open()的第二个参数规定了文件的打开模式,可选项有追加模式ios::app等; - 指针定位
seekg()seekp()是对文件内部进行随机访问的关键; <<流插入运算符和左移运算符重载,>>流提取运算符和右移运算符重载;- C++ 的流机制支持文件、字符串、数组等多种介质,I/O 具有多样性。
| 类 | 名称 | 描述 |
|---|---|---|
ifstream |
输入文件流 | 用于从文件读取信息 |
ofstream |
输出文件流 | 用于创建文件并向文件写入信息 |
fstream |
文件流 | 能同时读写文件 |
#include <fstream> // 文件流操作
#include <iostream> // 标准输入输出
using namespace std;
int main() {
char data[100];
// 1. 写入文件
ofstream outfile; // 创建输出文件流对象
outfile.open("afile.dat"); // 打开文件,写入模式 ios::out
if (!outfile.is_open()) { // 检查流对象是否关联了文件
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); // 从键盘读取一行,最多 100 个字符
outfile << data << endl; // 将姓名写入文件,并添加换行
cout << "Enter your age: ";
cin >> data;
cin.ignore(); // 清空输入缓冲区,消除上一次输入对下一次输入的影响
outfile << data << endl; // 将年龄写入文件
outfile.close(); // 关闭文件,确保数据写入磁盘
// 2. 读取文件
ifstream infile("afile.dat"); // 以读取模式打开文件
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;
}