C文件操作示例:逐行读取文本文件

闲来没事,封装了个用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;
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值