pavlos163
pavlos163

Reputation: 2890

Count number of 32-bit numbers in binary file

I am making a program where I should keep track of how many 32-bit numbers there are in a binary file.

For example when having as input a file that has in total 4x32 bits: 01001001010010010010100101001011010010001001010010010010100101000101010001001001010010010001000101001010010001001001001000000000

It should print 4.

I tried this with getc but it didn't work.

I think the solution has to do with fread but I'm not sure how exactly to use it in this problem.

int main() {
    FILE *fp = fopen("/home/pavlos55/GitRepo/arm11_1415_testsuite/test_cases", "rb");
    uint32_t number;
    uint32_t lines = 0;

    while (fread(&number, 4, 1, fp)) {
        lines++;
    }
    printf("%i", lines);
    return 0;
}

Can fread be in the condition. Why isn't this enough?

Thanks for any help.

Upvotes: 3

Views: 1246

Answers (2)

Filipe Gonçalves
Filipe Gonçalves

Reputation: 21213

You switched the 3rd and 4th arguments to fread(): with a uint32_t, you can read 4 elements of size 1, not 1 element of size 4. This is important to make sense out of what fread() returns: the actual number of elements read - this is what you need to add to lines. Here's a working version:

#include <stdio.h>
#include <stdint.h>

int main() {
    FILE *fp = fopen("test.c", "rb");
    uint32_t number;
    uint32_t lines = 0;
    size_t bytes_read;

    while ((bytes_read = fread(&number, 1, 4, fp))) {
        lines += bytes_read;
    }

    printf("%i\n", lines);
    return 0;
}

UPDATE: To count the number of 32-bit numbers, just divide lines by 4 after the loop:

lines /= 4;
printf("%i\n", lines);

Upvotes: 2

Mike Robinson
Mike Robinson

Reputation: 8945

A more pragmatic solution would be to fseek() to the end of the file, then use ftell() to obtain the resulting position. This will be "the size of the file in bytes."

Upvotes: 4

Related Questions