想法来源
由于在很多时候, 我们针对文件的操作都是针对于行进行的,尤其是只想根据某个文件的某一行或多行内容进行修改,这个时候就需要一个以行为单位进行文件管理的工具了,本文就是介绍了其中的某种实现
行操作需要考虑的问题
- 从文件加载所有行(load)
- 尾部追加行(append)
- 中间插入一行或多行(insert)
- 移除某一行或多行(remove)
- 读取某一行
- 修改某一行
- 遍历所有行(for)
- 获取总行数
- 保存更新后的行到文件
使用例程
/**
* usage example
*/
int main(int argc, char **argv)
{
FileLines lines("./test.txt");
std::cout << lines.tostring() << std::endl;
lines.append("4: 0987654321");
lines.save();
lines.refresh();
std::cout << lines.tostring() << std::endl;
return 0;
}
实现源码:
接口定义
/**
* filelines.h
*/
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
class FileLines
{
public:
FileLines();
explicit FileLines(const std::string& path);
/**
* @brief refresh
* @return
*/
bool refresh();
/**
* @brief refresh
* @param path
* @return
*/
bool refresh(const std::string& path);
/**
* @brief save
* @return
*/
bool save();
/**
* @brief save
* @param path
* @return
*/
bool save(const std::string& path);
int total() const;
/**
* @brief append add a new line to the end
* @param line
* @return
*/
int append(const std::string& line);
/**
* @brief clear all lines
*/
void clear();
/**
* @brief insertBefor