Search code examples
cbinaryfilesfread

How can you binary read blocks of data till EOF in C?


I try to learn to binary read blocks of data, instead to read the values one by one. I succesfully read the blocks which contains N bytes of data, but if the last block is not N bytes, the data is lost, because of the while condition.

#include<stdio.h>
#include<stdlib.h>

int main(){
int buffer[512];
FILE *data = fopen("new_file.bin","rb");
while( fread(&buffer,sizeof(int),512,data) )
{
... do something
}
return 0;
}

If the next block is for example 400 bytes, then the data from that block won't be used. Any idea how can I read all the data till EOF ?


Solution

  • Instead of reading N-byte blocks, you should read N 1-byte blocks.

    #include<stdio.h>
    #include<stdlib.h>
    
    #define N 2048
    
    int main(){
        char buffer[N];
        FILE *data = fopen("new_file.bin","rb");
        size_t size_read;
        while( (size_read = fread(buffer,1,N,data)) > 0 )
        {
            ... do something
        }
        return 0;
    }