使用缓冲区从未知大小的文件读取 [英] Using buffers to read from unknown size file

查看:173
本文介绍了使用缓冲区从未知大小的文件读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从文件读取块,我有一个问题。

I'm trying to read blocks from a file and I have a problem.

char* inputBuffer = new char[blockSize]
while (inputFile.read(inputBuffer, blockSize)) {
    int i = inputFile.gcount();
//Do stuff
}

假设我们的块大小 1024 bytes ,文件为 24,3 KiB 。读完第23块后,会有 0,3 KiB 左边读。我也想读取 0,3 KiB ,其实我以后使用 gcount()大多数缓冲区 read(...)修改(如果它更少)。

但是当它访问第24个块时, code> read(...)返回一个值,使程序不进入循环,显然是因为文件中剩余未读字节的大小小于缓冲区大小。我应该怎么办?

Suppose our block size is 1024 bytes, and the file is 24,3 KiB. After reading the 23rd block, there will be 0,3 KiB left to read. I also want to read that 0,3 KiB, in fact I use gcount() later so I can know how much of the buffer did read(...) modify (in case if it is less).
But when it accesses the 24th block, read(...) returns a value such that the program does not enter the loop, obviously because the size of the remaining unread bytes in the file is less than the buffer size. What should I do?

推荐答案

我认为你在另一个答案的评论中谈到的Konrad Rudolf阅读直到eof的问题。如果你从来没有到达eof因为一些其他的错误,你处在一个无限循环。所以,他的建议,但修改它,以解决您确定的问题。一种方法如下:

I think that Konrad Rudolf who you talk about in the comment to another answer makes a good point about the problem with reading until eof. If you never reach eof because of some other error you are in an infinite loop. So take his advice, but modify it to address the problem you have identified. One way of doing it is as follows;

bool okay=true;
while ( okay ) {
    okay = inputFile.read(inputBuffer, blockSize);
    int i = inputFile.gcount();
    if( i ) {
        //Do stuff
    }
}


b $ b

编辑:由于我的答案已被接受,我正在编辑它尽可能有用。原来我的bool好吧是完全不必要的(见ferosekhanj的答案)。最好直接测试inputFile的值,这也有优点,如果文件没有打开就可以优雅地避免进入循环。所以我认为这是这个问题的规范解决方案;

Since my answer has been accepted, I am editing it to be as useful as possible. It turns out my bool okay is quite unnecessary (see ferosekhanj's answer). It is better to test the value of inputFile directly, that also has the advantage that you can elegantly avoid entering the loop if the file did not open okay. So I think this is the canonical solution to this problem;

inputFile.open( "test.txt", ios::binary );
while ( inputFile ) {
    inputFile.read( inputBuffer, blockSize );
    int i = inputFile.gcount();
    if( i ) {
        //Do stuff
    }
}


b $ b

现在最后一次你做的东西,我会小于blockSize,除非在文件碰巧是blockSize字节长的倍数。

Now the last time you //Do stuff, i will be less than blockSize, except in the case that the file happens to be a multiple of blockSize bytes long.

Konrad Rudolf的回答这里也很好,它有优点是.gcount()只被调用一次,在循环外,但缺点是它真的需要将数据处理放在一个单独的函数中,以避免重复。

Konrad Rudolf's answer here is also good, it has the advantage that .gcount() is only called once, outside the loop, but the disadvantage that it really needs data processing to be put in a separate function, to avoid duplication.

这篇关于使用缓冲区从未知大小的文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆