C++二进制文件的读写
二进制文件的读取:
void readBinareFile(const std::string& filePath, std::vector<uint8_t>& data) {
std::ifstream ifs(filePath, std::ios::binary);
if (!ifs) {
SPDLOG_ERROR("failed to open read file: {}", filePath);
return;
}
// file size
ifs.seekg(0, std::ios::end);
std::streamsize size = ifs.tellg();
ifs.seekg(0, std::ios::beg);
data.resize(size);
ifs.read(reinterpret_cast<char*>(data.data()), size);
ifs.close();
}
二进制文件的写入:
void writeBinareFileOnce(const std::string& filePath, char* buffer, size_t size) {
std::ofstream ofs(filePath, std::ios::binary);
if (!ofs) {
SPDLOG_ERROR("failed to open write file: {}", filePath);
return;
}
ofs.write(buffer, size);
ofs.close();
}
实际操作中发现,较大文件分块写入的效率要高于一次性整体写入:
void writeBinareFile(const std::string& filePath, char* buffer, size_t size) {
std::ofstream ofs(filePath, std::ios::binary);
if (!ofs) {
SPDLOG_ERROR("failed to open write file: {}", filePath);
return;
}
size_t chunkSize = 32 * 1024;
size_t offset = 0;
while (offset < size) {
size_t size_to_write = std::min(chunkSize, size - offset);
ofs.write(buffer + offset, size_to_write);
offset += size_to_write;
}
ofs.close();
return;
}