可以编译,可结果出错,大家帮忙看一下
这是C++ primer书中的一个例子
text.txt中的内容为:
abcd
efg
hi
j
代码运行后text.txt中的内容修改为
abcd
efg
hi
j
5 9 12 14
程序的功能为,在文件的末尾写一个新行,该行包含每一行开头的相对位置。
我的调试环境为DEC++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream inout("text.txt",fstream::ate |fstream::in |fstream::out);
if(!inout)
{
cerr<<" Unable to open the file !"<<endl;
system("pause");
return -1;
}
ifstream::pos_type end_mark =inout.tellg();
inout.seekg(0,fstream::beg);
int cnt =0;
string line;
while(inout && inout.tellg() !=end_mark
&& getline(inout,line))
{
cnt=cnt+line.size()+1;
ifstream::pos_type mark = inout.tellg();
inout.seekp(0,fstream::end);
inout<<cnt;
if(mark !=end_mark) inout<<" ";
inout.seekg(mark);
}
inout.clear();
inout.seekp(0,fstream::end);
inout<<"\n";
system("pause");
return 0;
}