0

I'm doing CS50 (Week 4 Lab 4 Volume) and I have to copy a header from an input WAV file to output file (the 44 first bytes).

To start, I created the array uint8_t header[HEADER_SIZE];. Then, I used fread. But why the right solution is : fread(header, HEADER_SIZE, 1, input); and not something like : fread(header, sizeof(uint8_t), HEADER_SIZE, input);?

Don't it mean that all the header will be copied at once in the header array in a single element (which will lead to an error since an element must have 1 byte due to its type uint8_t)? Does the compiler now how to handle the situation when reading at once many bytes into an array with only 1 byte per element?

Thank you!

10
  • 1
    It could be. But here you need to read the whole header, so the element size is HEADER_SIZE and the number of elements is 1. The difference is that on success, fread with return 1 and HEADER_SIZE respectively. Commented Jun 27, 2022 at 9:30
  • Who says the second one is wrong? Did you try it? Commented Jun 27, 2022 at 9:31
  • 4
    You can read 1 item of size HEADER_SIZE or HEADER_SIZE items of size 1. What's the difference in the end? Besides of course, return value of fread will be different. Commented Jun 27, 2022 at 9:31
  • 1
    The bytes read from the file will not be stored in the first element but within the whole array. Commented Jun 27, 2022 at 9:49
  • 1
    Note that sizeof(char) is always 1 (by definition). So, using it in calculations is deprecated. A little tricky with sizeof(uint8_t) but don't use for the same reason. Strictly speaking, fread(header,sizeof(header),1,input) might be the best, but ... In glibc [linux], the size and nmemb are multiplied together as the first line of fread: size_t bytes_requested = size * count; and that is used internally. So, it's a bit of a moot point. read (the syscall) uses a byte count, so I do: fread(header,1,sizeof(header),input) to get a byte count return value Commented Jun 27, 2022 at 15:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.