<>中关于文件流的问题
我在调试<<c++primer>>p905页程序时,遇到问题一些问题
程序就是读取一个文本文件,依次统计一行内的字节数,将其写在文件末尾.
编译环境 vc2003
程序如下
#include <iostream>
#include <fstream>
int main()
{
using namespace std;
//书中打开文件用的是如下语句,但会文件会打开失败
//fstream inOut("e:\\test.dat",ios_base::in|ios_base::out|ios_base::app);
//ios_base::app 一定要和ios_base::out 一起用,才能实现追加?
//自己的打开语句
fstream inOut("e:\\test.dat",ios_base::in|ios_base::out|ios_base::app);
if(!inOut)
{
cerr<<"can not open file";
return -1;
}
int cnt=0;
char ch;
inOut.seekg(0);
while ( inOut.get( ch ))
{
cout.put( ch );
cnt++;
if ( ch == '\n' )
{
//这句为何提示出错呢?
//ios_base::pos_type mark = inOut.tellg();
int mark = inOut.tellg();
//追加操作时,写入文件,位置总是在文件尾部?
inOut.seekp(1000000);//原文中无此语句,但不加的话就不会追加数据到文件尾部
inOut << cnt<<' ' ;
inOut.seekg( mark ); // restore position
}
}
inOut.clear();
inOut << cnt << endl;
cout << "[ " << cnt << " ]\n";
inOut.close();
cin.get();
return 0;
}