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

前端 未结 3 1414
失恋的感觉
失恋的感觉 2021-02-20 15:32

So, here\'s my problem: I want to make a program that reads chunks of data from a file. Let\'s say, 1024 bytes per chunk. So I read the first 1024 bytes, perform various operati

相关标签:
3条回答
  • 2021-02-20 15:59

    Accepted answer doesn't work for me - it doesn't read last partial chunk. This does:

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

    Here UncompressedHandler accepts std::string, so I use constructor from two iterators.

    0 讨论(0)
  • 2021-02-20 16:02

    I think you missed up that there is a pointer points to the last place you've visit in the file , so that when you read for the second time you will not start from the first , but from the last point you've visit . Have a look to this code

    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
    

    so that how you may think about this concept .

    0 讨论(0)
  • 2021-02-20 16:03

    You can do this with a loop:

    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

    0 讨论(0)
提交回复
热议问题