c++ - 在 C++ 中读取和更改文件前 8 个字节的最快方法是什么?
问题描述
在 C++ 中读取和更改文件前 8 个字节的最快方法是什么?我不想将整个文件存储在内存中,因为如果我想编辑 10GB 文件的前 8 个字节,程序会非常慢,而且内存效率非常低。有没有办法先读取然后更改文件的前 n 个字节,而无需在内存中打开文件?
解决方案
您可以使用std::fstream
. 使用它的示例是:
仅适用于文本文件:
#include <fstream>
#include <iostream>
int main() {
std::fstream s("test.txt");
// read the data
char buff[8+1]{0};
s.read(buff, 8);
std::cout << "Data was: " << buff << '\n';
// handle case when reading reached EOF
if (!s) {
std::cout << "only " << s.gcount() << " could be read\n";
// clear the EOF bit
s.clear();
}
// back to beginning
s.seekp(0, std::ios_base::beg);
// overwrite the data
char data[] = "abcdabcd";
s.write(data, sizeof data);
}
对于二进制文件:
#include <fstream>
#include <iostream>
#include <iomanip>
int main() {
// need to pass additional flags
std::fstream s("test.mp4", std::ios_base::binary | std::ios_base::in | std::ios_base::out);
char buff[8 + 1] = {0};
s.read(buff, 8);
std::cout << "Data was: ";
for (auto i(0); i < s.gcount(); ++i) {
std::cout << '[';
std::cout << std::hex << std::setfill('0') << std::setw(2) << (0xFF & buff[i]);
std::cout << ']';
}
// handle case when reading reached EOF
if (!s) {
std::cout << "only " << s.gcount() << " could be read.";
s.clear();
}
// back to beginning
s.seekp(0, std::ios_base::beg);
char data[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
s.write(data, sizeof data);
}
推荐阅读
- macos - Mac os M1 Scikit-learn 模块找不到
- javascript - js this.form.submit(); 忽略所需的输入 html
- cmake - Cmake 无法调用自定义命令
- javascript - 空心圆盘的角速度 MatterJS
- python - Discord.py 如何使命令发生一定次数
- java - Java 内存 - 堆和非堆项
- linux - 一条指令可以分成不同的物理页面吗?
- pine-script - Pine 脚本正在将简单计算的结果从 int 转换为 series[float]
- javascript - 如何平滑地为圆角矩形的位置和大小设置动画?
- google-cloud-platform - 在 Google Cloud Platform 中创建组后,无法编辑组中的“网络端点组”和网络端点