一、读写文件方式
使用C++标准库的类,有三种方式可以处理文件读写,包括文本文件和二进制文件。cplusplus-fstream官网
方式 | 描述 |
---|---|
fstream | 输入输出文件,可以同时进行读写 |
ifstream | 输入文件,也就是读文件 |
ofstream | 输出文件,也就是写文件 |
二、文本文件示例
1、ifstream
当前场景每行每行读取,当然也可以read自定义读取
#include <fstream>
void readFromFile(const std::string& dictPath)
{
std::ifstream in(dictPath);
if (!in.is_open())
{
printf("dictPath is invalid!!\n");
return;
}
std::string line;
while (std::getline(in, line))
{
if (!line.empty()) //防止末尾有空行,越界
{
// 假设每行数据为 `675C杜`
std::string str1 = line.substr(0, 4); // 提取前四个字符
std::string str2 = line.substr(5); // 提取后面的文字
}
}
in.close();
}
2、ofstream
bool makeFile(const std::string& dictPath)
{
std::ofstream outputFile(dictPath);
if (outputFile.is_open()) {
std::string str1 = "hello";
std::string str2 = "world";
outputFile << str1 << "\t" << str2 << "\n"; // `\t`代表Tab制表符
outputFile.close();
}
else {
return false;
}
return true;
}