C++逐行读取文本文件的正确做法

作者:朱金灿

来源:http://blog.csdn.net/clever101

 

            之前写了一个分析huson日志的控制台程序,其中涉及到C++逐行读取文本文件的做法,代码是这样写的:

ifstream file;
file.open(“C:\\hudson.log”);
char szbuff[1024] = {0};
while(!file.eof())
{
		file.getline(szbuff,1024);
}

        开始这段代码运行是没有问题的,但后来运行居然出现了死循环,上网查了下资料,发现原因是:当缓冲区不够大的时候,getline函数也会对缓冲区输入数据,但同时也会把ifstream的状态位failbit设置了,于是fail函数会返回true。于是上述代码会嵌入死循环,由于处于fail状态下的ifstream,其getline函数不会再读入任何数据,因此后续的getline调用没有效果,并且fail函数一直返回true。

       

       正确的做法是:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
  char *filePath = "E:\\test.txt";
  ifstream file;
  file.open(filePath,ios::in);

  if(!file.is_open())

        return 0;

    
       std::string strLine;
       while(getline(file,strLine))
       {

            if(strLine.empty())
                continue;

            cout<<strLine <<endl;              
       }

}


参考文献:

 

1. getline的获取ifstream的数据


posted on 2015-08-18 18:30  岚之山  阅读(2170)  评论(0编辑  收藏  举报

导航