以块的形式读取文件

时间:2016-03-10 00:19:13

标签: c++ arrays memory file-io

char x[5];

ifstream i("test.txt", std::ifstream::binary);

while (i.read(x, sizeof(x))) { 
    ...
    bzero(x, sizeof(x));
}

如果文件字节大小不是5的倍数,则程序无法读取最后一个块。我如何确保阅读它?

1 个答案:

答案 0 :(得分:0)

怎么样:

std::ifstream fin("test.txt", std::ifstream::binary);
std::vector<char> x(5, 0);

while (fin.read(x.data(), x.size())) 
{
    std::streamsize s = fin.gcount();

    // do something with x's data
}