#include <iostream>
#include <fstream>
#include <cstdlib>
#include<cassert>
using namespace std;
void test1()
{
// ofstream out("E://data.txt");
ofstream out;
out.open("E://data.txt",ios_base::binary|ios_base::out);
assert(out);
int i ;
int count = 0 ;
for (i = 1 ; i <= 20 ; i ++ )
{
out<<(i)<<"/t";
}
out.close();
//ifstream in("E://data.txt");
ifstream in;
in.open("E://data.txt",ios_base::in|ios_base::binary);
assert(in);
while(!in.eof())
{
in>>i ;
cout<<i<<endl;
count++;
}
cout<<"Test1()/tcount = "<<count<<endl;
}
void test2()
{
ofstream out ;
out.open("D://data.dat",ios_base::out|ios_base::binary);
assert(out);
int size = 20 ;
for (int i = 0 ; i < 20 ; i ++ )
{
if(i==19)
out<<(i+1);
else
out<<(i+1)<<"/t";
}
/*上面循环向文件写入20个数据和20个TAB
所以结尾处应该为第20个Tab处
而不是第20个数据(20)的地方
*/
//out<<endl; 如果此句不注释,输出数据个数仍然比实际数据多一个
// Tab和endl的效果是一样的
// 流ifstream都会将它们忽略(读int数据时)
out.close();
int count = 0 ;
ifstream in ;
in.open("D://data.dat",ios_base::in|ios_base::binary);
assert(in);
while(! in.eof())
{
int tmp ;
in>>tmp ;
count ++ ;
}
/* 流ifstream读入int数据时,将忽略Tab、endl
该流结束的位置为第20个Tab位置处
(位于数据20之后的位置)
所以读完20后,指针不是eof,需要再次进入
while循环,因此count读入的数据个数会比实
际多一个
*/
in.close();
cout<<"Test2()/tcount="<<count<<endl;
}
int main()
{
test1();
test2();
getchar();
return 0 ;
}
学会时时刻刻思考,问题是因为假想某种情况才会出现的。实践-思考-实践。