c++ ifstream, ofstream, fstream 之2一览
- 上面是这几个类的继承关系,都需要包含
,ifstream输入,ofstream输出,fstream既输入又输出
ios::in 输入(读)
ios::out 输出(写)
ios::ate 初始位置:文件尾
ios::app 附加
ios::trunc 如果文件已存在则先删除该文件
ios::binary 二进制方式
ifstream 默认 ios::in
ofstream 默认 ios::out
fstream 默认 ios::in | ios::out
- 下面是一段小程序显示它们的用法:
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
// read file use fstream
std::fstream iofile("./status.txt", ios::in | ios::out);
if (iofile.fail())
{
fprintf(stderr, "cann't open status.txt \n");
return -1;
}
string strLine;
while (getline(iofile, strLine))
{
cout << strLine << endl;
// getchar();
}
iofile.close();
// write file use fstream
fstream outfile("./result.txt", ios::out | ios::app);
if (outfile.fail())
{
fprintf(stderr, "cann't create result.txt \n");
return -1;
}
int count = 0;
while (++count < 100)
{
outfile << count << endl;
}
outfile.close();
// read file use istream
ifstream infile("./status.txt"/*, ios::in (as default)*/);
if (infile.fail())
{
fprintf(stderr, "cann't open status.txt \n");
return -1;
}
while (getline(infile, strLine))
{
cout << strLine << endl;
//getchar();
}
infile.close();
// write file use ostream
ofstream ooutfile("./result2.txt"/*, ios::out | ios::trunc (as default) */);
if (ooutfile.fail())
{
fprintf(stderr, "cann't open status.txt \n");
return -1;
}
while (--count > 0)
{
ooutfile << count << endl;
}
ooutfile.close();
return 0;
}