Confusion with the parameters of C's fwrite function

I am now learning the C language. I came across fread and fwrite functions in tutorialspoint.com. Basically, the declaration for both of these functions are kinda the same:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)

There are some examples for each of these functions in that website. As for the fwrite function:

fwrite(str , 1 , sizeof(str) , fp );

And I can totally understand this. But as for the fread function:

fread(buffer, strlen(c)+1, 1, fp);

Why the 1 argument come after the strlen(c)+1 argument? Is this some kind of mistake or there is something I should know?

Thanks in advance.

Upvotes: 2

Views: 1113

Answers (3)

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

From here

Size - Size in bytes of each element to be written. size_t is an unsigned integral type.

Count - Number of elements, each one with a size of size bytes. size_t is an unsigned integral type.

You can interchange the size and the count and it will not make any difference in the normal case. As mentioned by 2501, it will make a difference if the no of elements cannot be read from the file.

The example given will work in the normal case, but should be corrected to give proper values for size and count for fread

fread(buffer, 1, strlen(c)+1, fp);

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409136

Reading e.g. this fread reference, or this fread POSIX specification tell us that the size argument is the size of each element (e.g. sizeof(some_type)), while nmemb is the number of elements to read (e.g. strlen(some_string)). The same goes for fwrite of course.

In most cases though, switching places of the values passed doesn't matter, if everything works okay then size * nmemb bytes will be read (or written). The problems comes when there's error reading from or writing to the file, so it's best to try and remember which argument is which.

Upvotes: 3

tdao
tdao

Reputation: 17678

Why the 1 argument come before the sizeof(str) argument?

1 is sizeof( char )

The fwrite should be better written as:

fwrite(str , sizeof(char) , sizeof(str) , fp );

Upvotes: 2

Related Questions