ngl_server 1.0
基于 Actor 模型的 C++ 服务器框架
ngl::tools::readfile Class Reference

文件读取类。 More...

#include <tools_file.h>

Public Member Functions

 readfile (const std::string &filename)
 构造函数,打开指定文件。
 ~readfile ()
 析构函数,自动关闭文件。
bool is_open () const
 查询文件是否成功打开。
int get_maxline ()
 获取文件总行数。
void jumpbegin (int anum, bool aiscsv)
 跳过文件开头的指定行数。
bool readline (std::string &aline)
 读取一行。
bool readcurrent (std::string &astr)
 从当前读取位置读取到文件末尾。
void read (std::string &aneirong)
 从文件开头读取完整内容。

Detailed Description

文件读取类。

封装std::ifstream,提供按行读取、整文件读取、 行数查询等功能。支持CSV模式正确处理引号内的换行符。

Note
不可拷贝,构造时打开文件,析构时自动关闭。
readfile rf("config.txt");
if (rf.is_open()) {
std::string line;
while (rf.readline(line)) {
process(line);
}
}

Constructor & Destructor Documentation

◆ readfile()

ngl::tools::readfile::readfile ( const std::string & filename)
explicit

构造函数,打开指定文件。

构造函数,打开文件进行读取

Parameters
filename文件路径
filename要打开的文件名

以二进制模式打开文件,避免换行符转换

Note
如果文件不存在,is_open()将返回false

◆ ~readfile()

ngl::tools::readfile::~readfile ( )

析构函数,自动关闭文件。

析构函数,确保文件被正确关闭

使用try-catch确保析构函数不会抛出异常

Member Function Documentation

◆ get_maxline()

int ngl::tools::readfile::get_maxline ( )

获取文件总行数。

获取文件总行数

Returns
int 文件行数(首次调用会遍历计算并缓存)
文件行数,如果文件未打开返回0

第一次调用时计算并缓存结果,后续调用直接返回缓存值 计算完成后恢复文件指针到原始位置,保持无副作用

Note
使用m_cached_maxline缓存结果

◆ is_open()

bool ngl::tools::readfile::is_open ( ) const

查询文件是否成功打开。

检查文件是否成功打开

Returns
true 文件已打开
false 文件未打开
文件已打开返回true,否则返回false

◆ jumpbegin()

void ngl::tools::readfile::jumpbegin ( int anum,
bool aiscsv )

跳过文件开头的指定行数。

跳过文件开头的指定行数

Parameters
anum要跳过的行数
aiscsv是否为CSV模式(CSV模式会正确处理引号内的换行符)
anum要跳过的行数
aiscsv是否为CSV格式(处理引号内的换行)

CSV模式下,引号内的换行不计入行数 非CSV模式下,简单跳过指定行数

◆ read()

void ngl::tools::readfile::read ( std::string & aneirong)

从文件开头读取完整内容。

读取整个文件内容

Parameters
aneirong输出参数,存储文件全部内容
aneirong[out] 存储文件全部内容

先获取文件大小,然后一次性读取 如果文件为空,aneirong会被清空

◆ readcurrent()

bool ngl::tools::readfile::readcurrent ( std::string & astr)

从当前读取位置读取到文件末尾。

从当前位置读取到文件末尾

Parameters
astr输出参数,存储读取的内容
Returns
true 读取成功
false 读取失败
Parameters
astr[in/out] 存储读取的内容(追加到末尾)
Returns
成功读取返回true,失败返回false

不会清空astr原有内容,而是追加新内容 用于增量读取文件

◆ readline()

bool ngl::tools::readfile::readline ( std::string & aline)

读取一行。

读取一行内容

Parameters
aline输出参数,存储读取的行内容
Returns
true 读取成功
false 到达文件末尾或读取失败
Parameters
aline[out] 存储读取的行内容
Returns
成功读取返回true,到达文件末尾返回false

自动去除行尾的'\r'字符(Windows换行符)


The documentation for this class was generated from the following files: