如何在 EOF (C++) 之前读取多个块中的文件

How to read a file in multiple chunks until EOF (C++)

本文关键字:读取 文件 EOF C++      更新时间:2023-10-16

所以,这是我的问题:我想创建一个从文件中读取数据块的程序。假设每个块 1024 字节。所以我读取了前 1024 个字节,执行各种操作,然后打开接下来的 1024 个字节,而不读取旧数据。程序应继续读取数据,未达到EOF。

我目前正在使用此代码:

std::fstream fin("C:\file.txt");
vector<char> buffer (1024,0); //reads only the first 1024 bytes
fin.read(&buffer[0], buffer.size());

但是如何读取接下来的 1024 个字节?我在思考使用 for 循环,但我真的不知道怎么做。我完全是C++菜鸟,所以如果有人能帮助我,那就太好了。谢谢!

你可以通过循环来做到这一点:

std::ifstream fin("C:\file.txt", std::ifstream::binary);
std::vector<char> buffer (1024,0); //reads only the first 1024 bytes
while(!fin.eof()) {
    fin.read(buffer.data(), buffer.size())
    std::streamsize s=fin.gcount();
    ///do with buffer
}

##EDITED

http://en.cppreference.com/w/cpp/io/basic_istream/read

接受的答案对我不起作用 - 它不会读取最后一个部分块。这样做:

void readFile(std::istream &input, UncompressedHandler &handler) {
    std::vector<char> buffer (1024,0); //reads only 1024 bytes at a time
    while (!input.eof()) {
        input.read(buffer.data(), buffer.size());
        std::streamsize dataSize = input.gcount();
        handler({buffer.begin(), buffer.begin() + dataSize});
    }
}

这里 UncompressedHandler 接受 std::string,所以我使用来自两个迭代器的构造函数。

我想你错过了一个指针指向你在文件中访问过的最后一个地方,所以当你第二次阅读时,你不会从第一个开始,而是从你访问的最后一个点开始。看看这个代码

std::ifstream fin("C:\file.txt");
char buffer[1024]; //I prefer array more than vector for such implementation
fin.read(buffer,sizeof(buffer));//first read get the first 1024 byte
fin.read(buffer,sizeof(buffer));//second read get the second 1024 byte

这样你就可以如何看待这个概念.

我认为这会起作用

     #include <stdlib.h>
     #include <stdio.h>
     #include <string.h>
     #include <fstream>
    
    // Buffer size 16 Megabyte (or any number you like)
    size_t buffer_size = 1 << 24; // 20 is 1 Megabyte
    char* buffer = new char[buffer_size];
    std::streampos fsize = 0;
    std::ifstream file("c:\file.bin", std::ios::binary);
    fsize = file.tellg();
    file.seekg(0, std::ios::end);
    fsize = file.tellg() - fsize;
    int loops = fsize / buffer_size;
    int lastChunk = fsize % buffer_size;
    for (int i = 0; i < loops; i++) {
        file.read(buffer, buffer_size);
        // DO what needs with the buffer
    }
    if (lastChunk > 0) {
        file.read(buffer, lastChunk);
        // DO what needs with the buffer
    }
    delete[] buffer;