闲来没事,封装了个用C逐行读取文本文件的类,直接贴代码:
CFileOp.h
#include <string>
#include <list>
class CFileOp
{
public:
//-----------------------------------------------------
// 读取文本文件的内容
// path[IN]
// 文件全路径
// lstLine[OUT]
// 文本文件的内容,每一行对应list中的一项,每行的内容不包含换行符'\r''\n'
// 返回值:
// 0 读取成功
// -1 读取失败,如文件不存在
//-----------------------------------------------------
static int ReadFileLineByLine(const std::string& path, std::list<std::string>& lstLine);
//-----------------------------------------------------
// 读取文本文件的一行
// fp[IN]
// 文件指针,必须保证为有效的文件指针并且不指向文件末尾.
// line[OUT]
// 返回读取的一行,不包含换行符'\r''\n'
//-----------------------------------------------------
static void ReadLine(FILE* fp, std::string& line);
};
CFileOp.cpp
#include "CFileOp.h"
int CFileOp::ReadFileLineByLine(const std::string& path, std::list<std::string>& lstLine)
{
lstLine.clear();
FILE* fp = fopen(path.c_str(), "r");
if (NULL == fp)
{
return -1;
}
std::string line;
while (1)
{
if (feof(fp))
{
break;
}
ReadLine(fp, line);
lstLine.push_back(line);
line = "";
}
fclose(fp);
return 0;
}
void CFileOp::ReadLine(FILE* fp, std::string& line)
{
static const unsigned int buf_size = 1024;
static char buffer[buf_size] = { 0 };
line = "";
while (1)
{
char* ch = fgets(buffer, buf_size, fp);
if (NULL == ch)
{
return;
}
line += ch;
if (line.empty())
{
return;
}
else
{
if (line.back() == '\n')
{
line.pop_back();
return;
}
}
}
}
使用示例:
#include <iostream>
#include <list>
#include <string>
#include "CFileOp.h"
using namespace std;
int main()
{
list<string> lstLine;
if (-1 == CFileOp::ReadFileLineByLine("D:\\123.txt", lstLine))
{
cout << "file not exist" << endl;
}
else
{
list<string>::iterator iterLine = lstLine.begin();
for (; iterLine != lstLine.end(); ++iterLine)
{
cout << *iterLine << endl;
}
}
return 0;
}