标准库提供了各种类型的流对象用于读写文本数据,这些流对象都符合文本流模型。 例如,可以使用fstream头文件中定义的fstream类型来读写文件:
#include
using namespace std;
int main()
{
// 创建一个文件输入流对象ifs并打开一个文件
ifstream ifs("example.txt");
if (!ifs) {
cerr << "Failed to open the file." << endl;
return 1;
}
// 创建一个文件输出流对象ofs并打开一个文件
ofstream ofs("output.txt");
if (!ofs) {
cerr << "Failed to open the file." << endl;
return 1;
}
// 从ifs中读入一行文本,然后写入ofs
string line;
while (getline(ifs, line)) {
ofs << line << endl;
}
return 0;
}
在代码中,我们使用了ifstream和ofstream类型的流对象来分别读取和写入文件。getline函数从ifs中读入一行文本数据,然后使用<<操作符写入ofs。这些操作符都符合文本流模型的要求。