C++ Exercises(九)

来源:互联网 发布:单片机前景 编辑:程序博客网 时间:2024/05/08 20:10

<<C++ Primer>>第三版P905的这个程序有很多问题想不明白:

#include <iostream>
#include 
<fstream>
using namespace std;

int main()
{
    fstream inOut( 
"D://copy.out", ios_base::in|ios_base::app);
    
int cnt=0;
    
char ch;
    inOut.seekg(
0);
    
    
while ( inOut.get( ch ) )
    
{
        cout.put( ch );
        cnt
++;
        
if ( ch == '/n' )
        
{
            streamoff  mark 
= inOut.tellg();// 标记当前位置
            inOut << cnt << ' ';
            inOut.seekg( mark ); 
// 恢复位置
        }

    }

    inOut.clear();
    inOut 
<< cnt << endl;
    cout 
<< "" << cnt << " ]/n";
    
return 0;
}

用下面的数据进行测试:

abcd
efg
hi
j


分别保存为data.txtcopy.out,运行结果:

abcd
efg
hi
[ 12 ]


后来我想可能是因为不是读的二进制的缘故,所以我改为:

 

fstream inOut( "D://data.txt", ios_base::in|ios_base::app|ios_base::binary);

分别进行测试后,结果就更奇怪了。

这是data.txt的:

abcd
efg
hi
[ 15 ]


这是copy.out的:

abcd
efg
j
[ 18 ]

 

这到底是为什么呢?

原创粉丝点击