读文件
时间:2010-08-26 来源:snailshen
TCTimeCost timea;
timea.Start();
char buf[1024*10];
int iFd = open("data.txt",O_RDONLY);
if(iFd == -1){
cout<<"open file:"<<"data.txt"<<" error!!!"<<endl;
return -1;
}
int isize = 0;
int pos,pos2;
string slastrec,srec;
while((isize = read(iFd,buf,8192))>0){
//cout<<"slastrec.size="<<slastrec.size()<<endl;
//cout<<"slastrec="<<slastrec<<endl;
if(slastrec.size()>0)
srec = slastrec + string(buf);
else
srec = buf;
//cout<<"srec="<<srec<<endl;
pos = pos2 = 0 ;
slastrec = "";
while((pos=srec.find("\n", pos))!= string::npos){
//cout<<"jf rec="<<srec.substr(pos2,pos-pos2)<<endl;
pos2 = ++pos;
}
int recsize = srec.size();
if(pos2<recsize)
slastrec = srec.substr(pos2,recsize-pos2);
}
close(iFd);
cout<<"read file time:"<<timea.Cost()<<endl;
timea.Start();
ifstream iFile("data.txt");
while(iFile.good()){
iFile.getline(buf, sizeof(buf));
//cout<<"rec="<<buf<<endl;
}
iFile.close();
cout<<"fstream file time:"<<timea.Cost()<<endl;
测试结果,源文件条数:1741条,可以看到用块读比一行一行读快60倍
read file time:10516
fstream file time:657857