1. txt文件读写
1.1 txt文件基本读写
在windows和linux下路径示意
//windows
std::string file_path = "C:/program/user/leetcode.txt";
//linux
std::string file_path = "/program/user/leetcode.txt";
1.1 基本读txt文件
#include <fstream>
/**
* @brief 读txt文件
* @param file_path 待读文件路径
* @param error_info 输出错误信息
*
* @return 输出文件信息的字符串
*/
std::string FileTool::ReadTxtFile(const std::string& file_path, std::string& error_info){
if (file_path.empty()) {
error_info = "file path is empty";
return "";
}
std::ifstream in_file;
in_file.open(file_path.c_str(), std::ios::in);
if (!in_file.is_open() || !in_file.good()) {
error_info = "打开" + file_path + "文件失败";
}
std::string file_string = "", line_string = "";
while (std::getline(in_file, line_string)) {
file_string += (line_string + "\n");
}
in_file.close();
return file_string;
}
1.2 基本写txt文件
#include <fstream>
/**
* @brief 写txt文件
* @param file_path 待写文件路径
* @param file_string 待写文件的字符串信息
* @param error_info 输出错误信息
*
* @return 输出文件信息的字符串
*/
bool FileTool::WriteTxtFile(const std::string& file_path,
const std::string& file_string,
std::string& error_info){
if (file_path.empty()) {
error_info = "file path is empty";
return "";
}
std::ofstream out_file;
//若文件不存在不会崩溃,会在此路径下创建file
out_file.open(file_path.c_str(), std::ios::out | std::ios::app);
if (!out_file.is_open() || !out_file.good()) {
error_info = "打开" + file_path + "文件失败";
return false;
}
out_file << file_string << '\n';
out_file.close();
return true;
}
1.2 txt文件处理
2.写
3.创建
2. json文件读写
json(JavaScript Object Notation)是一个轻量的数据交换格式。
RapidJSON 是一个 C++ 的 JSON 解析器及生成器,具有小而全、速度快、相对独立、对内存友好等特点。详细的json读写参考以下文章。