我不擅长C而且我正在尝试做一些简单的事情。我想打开一个二进制文件,读取1024字节数据的块并转储到缓冲区,处理缓冲区,读取另外1024个数据的数据并继续这样做直到EOF。我知道我想用缓冲区做什么/我想做什么,但这是我一直坚持的循环部分和文件I / O.
PSEUDO代码:
FILE *file;
unsigned char * buffer[1024];
fopen(myfile, "rb");
while (!EOF)
{
fread(buffer, 1024);
//do my processing with buffer;
//read next 1024 bytes in file, etc.... until end
}
答案 0 :(得分:15)
fread()
返回读取的字节数。你可以循环直到那个为止。
FILE *file = NULL;
unsigned char buffer[1024]; // array of bytes, not pointers-to-bytes
size_t bytesRead = 0;
file = fopen(myfile, "rb");
if (file != NULL)
{
// read up to sizeof(buffer) bytes
while ((bytesRead = fread(buffer, 1, sizeof(buffer), file)) > 0)
{
// process bytesRead worth of data in buffer
}
}