1

At first I could not get fread() to read anything from card.raw, but then I made a change to the second and third arguments, and the function worked. Although intuition led me to the change, the two versions look equivalent to me.

Can someone explain why the first version did not read any elements (meaning the fread() returned 0), whereas the second did?

For the sake of other learners, I'm only including the code that I think is relevant to the question.

Outside of main:

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

typedef uint8_t BYTE;

In main:

BYTE buffer[512];

First version of fread() (did not work):

while (fread(buffer, sizeof(BYTE), 512, card_file) == 1)

This version failed the first test, returning 0 and thus false, never entering the while loop.

Second version of fread() (worked, e.g. read all 512B blocks of data):

while (fread(buffer, sizeof(buffer), 1, card_file) == 1)

While I'm glad I got the program to work, it bugs me that I don't understand the difference between the two versions of fread().

2

Are you sure that you haven't switched the working version for the non-working one? fread() requires 4 parameters. Because of your placement of parentheses, the second one only has one parameter, fread(buffer)

However, let's assume that this is merely a copying error and move on. You said that the first one failed, but you don't describe the nature of the fail. Does it not compile? Does it simply not enter the while loop? I'm betting that it is the latter.

The problem is the test itself. Consider the second and third parameters, and the value returned by fread(). The second parameter is the size of each element read. The third parameter is the number of elements to be read, actually, the maximum number of elements. If the read hits an EOF, the number of elements can be smaller. The return value is the actual number of elements read, but not the total number of bytes.

So, the second test works(notwithstanding the typo) because it is reading 1 element of 512 bytes or sizeof(buffer), and 1==1, so the test passes. The first version doesn't work because it reads 512 elements of 1 byte or sizeof(BYTE), and 512 does NOT equal 1. If you change the ==1 to == 512 it should work, providing there aren't other issues.

You might want to spend some time reviewing the docs for fread() to get a better understanding.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

| improve this answer | |
  • Thanks for the response. The second test did have a typo, which I edited. Your answer was spot on. I changed the first test as you suggested, and the program worked beautifully. – Darren Rippy Feb 13 '16 at 13:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .