读取文件
#include <fstream>
int main()
{
std::string path = "./a.txt";
std::filesystem::path file_0(path);
if (!std::filesystem::exists(file_0))
{
cout << read_path << "不存在" << endl;
return 1;
}
std::ifstream ifs;
ifs.open(path, std::ios::out | std::ios::binary);
if (!ifs.is_open())
{
std::cout << "文件打开失败" << std::endl;
}
ifs.seekg(0, std::ios::end);
std::size_t length = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::cout << "length: " << length << std::endl;
unsigned char* file_data = (unsigned char*)malloc(sizeof(unsigned char) * length);
ifs.read(reinterpret_cast<char*>(file_data), length);
ifs.close();
free(file_data);
return 0;
}
结果:length: 51
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/46d1381a76dc2d134592dd6f7713fb77.png)
写入文件
struct data
{
int id;
std::string one;
float two;
};
#include <boost\timer.hpp>
#include <fstream>
int main()
{
std::ofstream ofs;
ofs.open("./text2.txt", ios::out);
boost::timer one1;
one1.restart();
struct data temp;
temp.one = "2023-06-07 00:00:00";
for (int i = 0; i < 100000000; i++)
{
temp.id = i;
temp.two = 5.5;
ofs << temp.id <<" " << temp.one << " " << temp.two << std::endl;
}
std::cout << "用时:" << one1.elapsed() << "秒 , " << one1.elapsed() / 60 << " 分钟 " << std::endl;
ofs.close();
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/19c6afdab5af56ee44119f7c30bd18bf.png)