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

来源:互联网 发布:java 多用户 博客 编辑:程序博客网 时间:2024/04/29 21:22

作者:朱金灿

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

 

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

[cpp] view plain copy
  1. ifstream file;  
  2. file.open(“C:\\hudson.log”);  
  3. char szbuff[1024] = {0};  
  4. while(!file.eof())  
  5. {  
  6.         file.getline(szbuff,1024);  
  7. }  

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

       

       正确的做法是:

[cpp] view plain copy
  1. #include <iostream>  
  2. #include <fstream>  
  3. #include <string>  
  4.   
  5. using namespace std;  
  6.   
  7. int main()  
  8. {  
  9.   char *filePath = "E:\\test.txt";  
  10.   ifstream file;  
  11.   file.open(filePath,ios::in);  
  12.   
  13.   if(!file.is_open())  
  14.   
  15.         return 0;  
  16.   
  17.       
  18.        std::string strLine;  
  19.        while(getline(file,strLine))  
  20.        {  
  21.   
  22.             if(strLine.empty())  
  23.                 continue;  
  24.   
  25.             cout<<strLine <<endl;                
  26.        }  
  27.   
  28. }  


参考文献:

 

1. getline的获取ifstream的数据

阅读全文
0 0
原创粉丝点击