怎样实现文件行数问题?
例如有一个文件 raw.txt
里面的数据是怎样组织的都可以,怎样才能求出里面的数据一共有几行呢?要求用C/C++文件操作实现,速度要尽可能快。
由于文件方面学得差,希望各位指教下。
谢谢!!!
[解决办法]
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
long lCount=0;
string s;
ifstream fin( "raw.txt ");
while(readline(fin,s)) ++lCount;//每读一行,只计数而不要做别的,这要就快些.
cout < < "Lines of raw.txt : " < <lCount < <endl;
}
[解决办法]
一次读几K的字节,然后统计 '\n '数目。二楼的方法效率不高。
[解决办法]
windows下用CreateFileMapping,MapViewOfFile
linux下用mmap,
然後直接計統計有多少個 '\n ',
最後字符如不是 '\n ',再加 1,
這樣要更快一點
[解决办法]
size_t Statistic(const char *pFileName)
{
ifstream infile(pFileName,ios::binary);
if( infile.fail() ){ return -1; }
istreambuf_iterator <char> bg(infile);
istreambuf_iterator <char> ed;
return count(bg,ed, '\n ');
}