使用Qt的QFile读取文件,直接上代码,支持换行符\r, \n, \r\n
static int GetFileRows(const QString &file)
{
int line = 0;
QFile fi(file);
if(!fi.open(QIODevice::ReadOnly))
{
return -1;
}
bool pre_is_r = false;
QString ch;
QTextStream stream(&fi);
while(!stream.atEnd())
{
ch = stream.read(1);
if(ch == "\n")
{
if(!pre_is_r) // \n
++line;
else // \r\n
pre_is_r = false;
}
else if(ch == "\r") //\r
{
++line;
pre_is_r = true;
}
else //other character
{
pre_is_r = false;
}
}
fi.close();
return line + 1;
}