Какой самый быстрый способ прочитать и изменить первые 8 байтов файла в C ++? - PullRequest
0 голосов
/ 07 марта 2020

Какой самый быстрый способ прочитать и изменить первые 8 байтов файла в C ++? Я не хочу хранить весь файл в памяти, потому что, если я хочу отредактировать первые 8 байтов файла 10 ГБ, программа будет очень медленной и очень неэффективной. Есть ли способ сначала прочитать, а затем изменить первые n байтов файла, не открывая файл в памяти?

1 Ответ

0 голосов
/ 07 марта 2020

Вы можете получить то, что вы хотите, используя 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);
}
...