前言
有时要写个简单的文件IO程序,却忘了步骤。郁闷。这次整一个标准的模板代码,忘了来查就好了。
示例1:(如下代码从标准输入获取字符串并写入到文件)
示例2:(如下代码读取一个文件并将其内容输出到屏幕)
有时要写个简单的文件IO程序,却忘了步骤。郁闷。这次整一个标准的模板代码,忘了来查就好了。
示例1:(如下代码从标准输入获取字符串并写入到文件)
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream out;
string file1;
cout << "Which file do you like to write ?" << endl;
cin >> file1;
/*
* Open file
*/
out.open(file1.c_str());
if (out) {
cout << "File \"" << file1 << "\" Open successfully." << endl;
}
else {
cout << "There is no such file." << endl;
return 1;
}
/*
* Travers file
*/
string s;
while (cin >> s) {
s += " ";
out << s;
}
cout << "Work has been done." << endl;
/*
* Something has to be done, you konw it :)
*/
out.close();
out.clear();
return 0;
}
示例2:(如下代码读取一个文件并将其内容输出到屏幕)
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream in;
string file1;
cout << "Which file do you like to read ?" << endl;
cin >> file1;
/*
* Open file
*/
in.open(file1.c_str());
if (in) {
cout << "File \"" << file1 << "\" Open successfully." << endl;
}
else {
cout << "There is no such file." << endl;
return 1;
}
/*
* Travers file
*/
string s;
while (in >> s) {
cout << s << " "; // "cout" can be instead by some other functions.
}
cout << endl;
/*
* Something has to be done, you konw it :)
*/
in.close();
in.clear();
return 0;
}