c++ - 如何(重新)在文件中间写入字节?

标签 c++ file file-io io

我有一个情况,文件中间有一个字节 block 需要重新洗牌。目前的实现读取文件,在内存中打乱字节,然后输出整个文件。虽然这有效,但它不能扩展为更大的文件大小。我还没有找到一个 C++ API,它允许我将特定数量的字节写入特定偏移量的文件,而不会影响后面的字节。

这可以做到吗?

最佳答案

fstream(不是 ifstreamofstream)开始,因为您同时进行输入和输出。

要进行改组,您基本上需要使用 seekg 到达您想要开始更改内容的位置。然后使用 read 读取您要洗牌的数据。然后在内存中打乱数据,使用 seekp 寻找你想要写回数据的地方,最后使用 write 将打乱的数据放回文件中.

这是一个快速演示,从字面上理解“洗牌”部分——它向文件写入一个字符串,然后读入一些数据,对这些字节进行排序,然后将它们写回:

#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>

void init(std::string const &name) { 
    std::ofstream initial(name);

    initial << "This is the initial data.";
}

void shuffle(std::string const &name) {
    std::fstream s(name);

    s.seekg(2);
    std::vector<char> data(5);
    s.read(&data[0], 5);
    std::sort(data.begin(), data.end());
    s.seekp(2);
    s.write(&data[0], 5);
}

void show(std::string const &name) { 
    std::ifstream in(name);

    std::copy(std::istreambuf_iterator<char>(in),
              std::istreambuf_iterator<char>(),
              std::ostream_iterator<char>(std::cout, ""));
}

int main() { 
    std::string name("e:/c/source/trash.txt");
    init(name);

    shuffle(name);

    show(name);
}

关于c++ - 如何(重新)在文件中间写入字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16202067/

相关文章:

c++ - 使用 SDL2 和 MinGW 诊断 DLL 问题

javascript - 显示所选文件的名称

c# - 为什么当另一个进程打开文件时 TextReader 会报错?

c - 如何用 fwrite() 覆盖偏移量 Y 上的 X 个字节?

c - 打开时出现段错误

c++ - 如何初始化一个指向结构体指针数组的变量?

c++ - 了解着色器编程

c++ - 节点插入cpp

javascript - 使用 javascript 提取并探索 .ZIP 文件夹中的文件修改时间戳

file - 如何将结构作为二进制数据写入golang中的文件?