计算文本文件中的行数

Count number of lines in a text file

本文关键字:文本 文件 计算      更新时间:2023-10-16

我需要计算文本文件中的行数。这是我现在掌握的代码。

CStdioFile sampleFile;
sampleFile.Open("test.txt",CFile::modeRead );
long length = 1;
CString row("");
while(sampleFile.ReadString(row))
{
    length++;
}

这不起作用。我没有得到文本文件中正确的行数值。这是怎么回事?

谢谢。

要读取Unicode文本文件,您可能需要检查CStdioFile派生的实现:来自代码项目的CStdioFileEx:

http://www.codeproject.com/Articles/4119/CStdioFile-derived-class-for-multibyte-and-Unicode

length应该初始化为0而不是1,因为您还没有读取第一行:

CString row;
long length = 0;
while (sampleFile.ReadString(row))
{
    length++;
}

尝试从0:开始计数

long length = 0;