随手写了段代码,碰到文件末尾时可能有bug,凑合着看吧:
int read_block(char *buf);
int anysize_reader(char *buf, int size)
{
static int staticBufSize;
static char staticBuf[4096];
//记录每次读了多少字节
int readBytes = 0;
//记录要返回的总共的字节数
int readCount = 0;
//如果缓存里有东西,优先把这部分放进buf
if(staticBufSize > 0)
{
//看要从缓存里取多少字节
readBytes = staticBufSize > size ? size :
staticBufSize;
//复制缓存内容进buf
memcpy(buf, &staticBuf[4096 - staticBufSize],
readBytes);
//缓存减少了
staticBufSize -= readBytes;
//要读的字节数减少了
size -= readBytes;
//读取了这么多字节
readCount += readBytes;
}
//如果缓存中的内容没有填满buf,就用read_block读新的内容
while(size > 0)
{
//预计读4k字节,碰到文件结尾可能不足这个数
readBytes = read_block(staticBuf);
if(readBytes < size)
{
//读取的字节数不足以满足需要时,把所有的
内容复制过去,继续读
memcpy(&buf[readCount], staticBuf,
readBytes);
readCount += readBytes;
size -= readBytes;
}
else
{
//读取的字节数大于需要时,留一部分在缓存里
memcpy(&buf[readCount], staticBuf, size);
readCount += size;
//记录缓存尾部留下了多少字节
staticBufSize = readBytes - size;
break;
}
}
return readCount;
}