首页 > 解决方案 > 在 C++ 中读取和更改文件前 8 个字节的最快方法是什么?

问题描述

在 C++ 中读取和更改文件前 8 个字节的最快方法是什么?我不想将整个文件存储在内存中,因为如果我想编辑 10GB 文件的前 8 个字节,程序会非常慢,而且内存效率非常低。有没有办法先读取然后更改文件的前 n 个字节,而无需在内存中打开文件?

标签: c++freadfseek

解决方案


您可以使用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);
}

推荐阅读