有一个标本txt文件,每行最后是\r\n结尾,每行长度不一致,请问如果高效地统计这个txt有多少行?

解决方案 »

  1.   

    每行长度不一致的话,只能用CStdioFile::ReadString()读一行数一行这个笨方法了。
      

  2.   

    也可用_getts(TCHAR* buffer);
    Get a line from the stdin stream.
      

  3.   

    仔细一想:不对,有一个好的方法!
    1 先把全部文本内容读进一个CString str中(如果你的文件不是大得离谱的话);
    2 用CString的Replace方法,替换换行符"\r\n",它的返回值int LineNumber=str.Replace("\r\n","");就是换行符的个数,即多少行。文件大的话就分几次读,一般一次读1M的话比较好一些。
      

  4.   

    代码如下:
    #include <afx.h>
    #include <iostream.h>void main()
    {
    CString str="";
    CFile file("f:\\test.txt",CFile::modeRead);
    char* temp=new char[file.GetLength()+1];
    memset(temp,0,file.GetLength()+1);
    file.Read(temp,file.GetLength());
    str=temp;
    int LineNumber=str.Replace("\r\n","");
    file.Close();
    delete temp;
    temp=NULL;
    cout<<"文件共有"<<LineNumber+1<<"行"<<endl;   //别忘了要加1
    }在我的机器上(系统XP,VC++6.0)测试通过,自己手工数的时候要注意减去那些自动换行的行数,因为它们不能算一行。