writing to text file
在头文件fstream中定义了一个ofstream的类(output file stream),这个类可以生成用于文件输出的对象.
不要搞混这里的输入和输出,output和input应该是针对于内存而言的,例如cout是从内存缓冲区到屏幕,ofstream是从内存缓冲区输出到文件.
可以参考标准输入来理解ofstream,如:
1.cout本身便是一个由ostream定义的对象(不是类),但是cout的定义隐藏在头文件中了.ofstream是一个类似于ostream的类,但是我们需要自己手动来定义一个对象.
-
ofstream这个element同样位于std命名空间内.
-
使用ofstream类中的open方法来打开文件,从而绑定我们手动创建的对象和文件.
reading from file(input to memory)
#include <iostream>
#include <fstream>
//include some system funcs
#include <cstdlib>
const int SIZE = 60;// In C++,always using const variable to replace the #define
using namespace std;
int main(int argc, char *argv[])
{
char filename[SIZE];
ifstream inFile;
cout << "please input the file name " << endl;
cin.getline(filename,SIZE);//read a string not longer than the SIZE
inFile.open(filename);//use the name array as the parameter
//detecting the file is open or not
if(!inFile.is_open())
{
cout << "the file is not open correctly !" <<endl;
cout <<"TERMINATED" <<endl;
exit(EXIT_FAILURE);//is Defined in cstdlib
}
double value;
double sum = 0.0;
int count = 0;
inFile >> value;
while(inFile.good())//inFile.good is familiar to isopen()
{
++count;
sum += value;
inFile >> value;
}
if (inFile.eof())
{
cout << "sucussecfully read" << endl;
}
else if (inFile.fail())
cout << "terminated by data mismatch" <<endl;
else
cout << "unknown erro" << endl;
if(cout == 0)
{
cout << "no data" << endl;
}
else
{
cout << "items " << count << endl;
cout << "sums " << sum <<endl;
cout << "Average " << sum/count << endl;
}
//dont forget to close the file
inFile.close();
return 0;
}
以上代码来自原书,加上自己的一些注释。要注意的是是否正确打开的检查,以及用于检测异常的方法。
浙公网安备 33010602011771号