1

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?

  • Shouldn't your other example counteract what you are saying by using another type? Anyway, all `fread` does is read `size * count` elements so you don't have to do the multiply yourself, and you can count in 'natural' numbers of the 'natural' size of your object. – Jongware Apr 15 '15 at 22:10
  • endianess deals with the order of individual bytes within an integer (that's larger than 1 byte). You seem to be dealing with individual bytes (chars) in both examples, in which there's no endianess issue. Though if you're doing funny stuff later on with that char array, you should tell us what you do, – nos Apr 15 '15 at 23:34

2 Answers2

1

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

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
0

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.

Community
  • 1
  • 1
Ulfalizer
  • 4,664
  • 1
  • 21
  • 30
  • Yeah, still depends on the interpretation of the data. I was assuming a plain `char` array with independent elements. – Ulfalizer Apr 15 '15 at 21:49