簡體   English   中英

在 C++ 中讀取和更改文件的前 8 個字節的最快方法是什么?

[英]What is the fastest way to read and change the first 8 bytes of a file in C++?

在 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM