Usqampa Damuth
Usqampa Damuth

Reputation: 53

fread and endianness: will fread(pointer,sizeof(some),1,file pointer) have the same result?

Suppose I have:

FILE* fp = fopen("myfile.bin", "r");
char something[30];
fread(something,sizeof(char)*30,1,fp);

For fread(something,sizeof(char),30,fp), endianness matters, but for the above code, does endianness matter?

Upvotes: 1

Views: 310

Answers (2)

Giorgi Moniava
Giorgi Moniava

Reputation: 28664

For fread(something,sizeof(char),30,fp), endianness matters, but for the above code, does endianness matter?

Why do you think those two snippets are different as far as endianness is concerned? To me they both read 30 bytes of data - albeit slightly differently, one specifies in arguments to read one element of size 30 and the other one, specifies it other way around.

But again till now you have just read some number of bytes. Now how you interpret these bytes is where endianness might come in. Read more on endianness: here. Then it depends if you just read some ASCII text endianness might not apply, if you read integer written in binary way endianness might be concern.

ps Also you might want to specify rb in fopen

Upvotes: 1

Ulfalizer
Ulfalizer

Reputation: 4752

Endianess won't matter for either case when reading into a char array. For cases where endianess does matter, how you specify the total size won't matter.

It's more of a historical artifact that fread() takes both a size and an nmemb parameter. The only difference you're likely to see is in the return value, which is a count in size units.

Excuse the self-plug, but you can find some source code analysis for glibc in this answer. The gist of it is that size and nmemb are simply multiplied together, with the separated values only being used to calculate the return value.

Upvotes: 0

Related Questions