Number of 32-bit numbers in a binary file

I am making a program where I have to keep track of how many 32 bit numbers there are in a binary.

For example, when entering a file that has a total of 4x32 bits: 01001001010010010010100101001011010010001001010010010010100101000101010001001001010010010001000101001010010001001001001000000000

It should print 4.

I tried it with help getc

but it didn't work.

I think the solution is relevant to 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;
}

      

May fread

be able to. Why is this not enough?

Thanks for any help.

+3


source to share


2 answers


You switched the 3rd and 4th arguments to fread()

: with uint32_t

you can read 4 elements of size 1, not 1 element of size 4. It's important to understand what it returns fread()

: the actual number of elements read is what you need to add in 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, simply divide lines

by 4 after the loop:

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

      

+2


source


A more pragmatic solution would be fseek()

to the end of the file, then use ftell()

to get the resulting position. This will be the "file size in bytes".



+4


source







All Articles