前言
本文分析两个经典的C++文件IO程序,提炼出其中文件IO的基本套路,留待日后查阅。
程序功能
程序一打印用户指定的所有文本文件,程序二向用户指定的所有文本文件中写入数据。
程序一代码及其注释
#include <iostream>
#include <fstream> // 使用文件处理对象记着要包含这个头文件
#include <string>
#include <vector> using namespace std; int main()
{
/*
* 获取用户需要打开的所有文件名,将其保存在顺序容器files中。
*/
string filename;
vector<string> files;
cout << "请输入要处理的文本文件名( ctrl+d结束 ):" << endl;
while (cin >> filename) {
files.push_back(filename);
cout << "请输入要处理的文本文件名( ctrl+d结束 ):" << endl;
}
cout << endl << "文件名录入完毕..." << endl << endl; /*
* 遍历文件名,并输出各个文件。
*/
// 创建一个流对象
fstream io;
for (vector<string>::iterator it = files.begin(); it != files.end(); it++) {
// 打开文件
io.open(it->c_str());
// 打开文件失败的异常处理
if (!io) {
cout << "文件 " << it->c_str() << " 打开失败!" << endl;
continue;
}
/*
* 打印文件内容
*/
cout << "文件: " << it->c_str() << endl;
string s;
while (getline(io, s))
cout << s << endl;
cout << endl << "文件" << it->c_str() << "读取完毕" << endl << endl << endl;
// 重置流前要先关闭流
io.close();
// 重置流
io.clear();
} // 使用完流关闭流。
io.close(); return ;
}
自行上机体验,不在此运行演示。
程序二代码及其注释
#include <iostream>
#include <fstream> // 使用文件处理对象记着要包含这个头文件
#include <string>
#include <vector> using namespace std; int main()
{
/*
* 获取用户需要打开的所有文件名,将其保存在顺序容器files中。
*/
string filename;
vector<string> files;
cout << "请输入要处理的文本文件名( #结束 ):" << endl;
while (cin >> filename) {
if (filename=="#") break;
files.push_back(filename);
cout << "请输入要处理的文本文件名( #结束 ):" << endl;
}
// 清空输入缓冲区
cin.ignore(, '\n');
cout << endl << "文件名录入完毕..." << endl << endl; /*
* 遍历文件名,并依次往文件中写入数据。
*/
fstream io;
for (vector<string>::iterator it = files.begin(); it != files.end(); it++) {
// 打开文件
io.open(it->c_str());
// 打开文件失败的异常处理
if (!io) {
cout << "文件 " << it->c_str() << " 打开失败!" << endl;
continue;
}
/*
* 往文件写入数据
*/
cout << "文件: " << it->c_str() << "( 单行输入#结束写入 )" << endl;
string s;
while (getline(cin, s)) {
if (s == "#") break;
io << s << endl;
}
cout << endl << "文件" << it->c_str() << "写入完毕" << endl << endl << endl;
// 重置流前要先关闭流
io.close();
// 重置流
io.clear();
} // 使用完流关闭流
io.close(); return ;
}
自行上机体验,不在此运行演示。
说明
1. 我之所以选用的例子是处理多个文件而不是单个文件,是想在代码中体现出用单个流对象处理多个文件的技巧。
2. 文件IO操作还有许多功能,诸如控制打开模式,获得流状态等等。详情参考各C++教材。