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.
You switched the 3rd and 4th arguments to
fread()
: with auint32_t
, you can read 4 elements of size 1, not 1 element of size 4. This is important to make sense out of whatfread()
returns: the actual number of elements read - this is what you need to add tolines
. Here's a working version:UPDATE: To count the number of 32-bit numbers, just divide
lines
by 4 after the loop: