大家好,又见面了,我是全栈君。
本文分析两个经典的C++文件IO程序,提炼出其中文件IO的基本套路,留待日后查阅。
程序一打印用户指定的所有文本文件,程序二向用户指定的所有文本文件中写入数据。
1 #include <iostream>
2 #include <fstream> // 使用文件处理对象记着要包含这个头文件
3 #include <string>
4 #include <vector>
5
6 using namespace std;
7
8 int main()
9 {
10 /*
11 * 获取用户需要打开的所有文件名,将其保存在顺序容器files中。
12 */
13 string filename;
14 vector<string> files;
15 cout << "请输入要处理的文本文件名( ctrl+d结束 ):" << endl;
16 while (cin >> filename) {
17 files.push_back(filename);
18 cout << "请输入要处理的文本文件名( ctrl+d结束 ):" << endl;
19 }
20 cout << endl << "文件名录入完毕..." << endl << endl;
21
22 /*
23 * 遍历文件名,并输出各个文件。
24 */
25 // 创建一个流对象
26 fstream io;
27 for (vector<string>::iterator it = files.begin(); it != files.end(); it++) {
28 // 打开文件
29 io.open(it->c_str());
30 // 打开文件失败的异常处理
31 if (!io) {
32 cout << "文件 " << it->c_str() << " 打开失败!" << endl;
33 continue;
34 }
35 /*
36 * 打印文件内容
37 */
38 cout << "文件: " << it->c_str() << endl;
39 string s;
40 while (getline(io, s))
41 cout << s << endl;
42 cout << endl << "文件" << it->c_str() << "读取完毕" << endl << endl << endl;
43 // 重置流前要先关闭流
44 io.close();
45 // 重置流
46 io.clear();
47 }
48
49 // 使用完流关闭流。
50 io.close();
51
52 return 0;
53 }自行上机体验,不在此运行演示。
1 #include <iostream>
2 #include <fstream> // 使用文件处理对象记着要包含这个头文件
3 #include <string>
4 #include <vector>
5
6 using namespace std;
7
8 int main()
9 {
10 /*
11 * 获取用户需要打开的所有文件名,将其保存在顺序容器files中。
12 */
13 string filename;
14 vector<string> files;
15 cout << "请输入要处理的文本文件名( #结束 ):" << endl;
16 while (cin >> filename) {
17 if (filename=="#") break;
18 files.push_back(filename);
19 cout << "请输入要处理的文本文件名( #结束 ):" << endl;
20 }
21 // 清空输入缓冲区
22 cin.ignore(1024, '\n');
23 cout << endl << "文件名录入完毕..." << endl << endl;
24
25 /*
26 * 遍历文件名,并依次往文件中写入数据。
27 */
28 fstream io;
29 for (vector<string>::iterator it = files.begin(); it != files.end(); it++) {
30 // 打开文件
31 io.open(it->c_str());
32 // 打开文件失败的异常处理
33 if (!io) {
34 cout << "文件 " << it->c_str() << " 打开失败!" << endl;
35 continue;
36 }
37 /*
38 * 往文件写入数据
39 */
40 cout << "文件: " << it->c_str() << "( 单行输入#结束写入 )" << endl;
41 string s;
42 while (getline(cin, s)) {
43 if (s == "#") break;
44 io << s << endl;
45 }
46 cout << endl << "文件" << it->c_str() << "写入完毕" << endl << endl << endl;
47 // 重置流前要先关闭流
48 io.close();
49 // 重置流
50 io.clear();
51 }
52
53 // 使用完流关闭流
54 io.close();
55
56 return 0;
57 }自行上机体验,不在此运行演示。
1. 我之所以选用的例子是处理多个文件而不是单个文件,是想在代码中体现出用单个流对象处理多个文件的技巧。
2. 文件IO操作还有许多功能,诸如控制打开模式,获得流状态等等。详情参考各C++教材。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/108677.html原文链接:https://javaforall.cn