0

in volume you have to fread() and fwrite() a wav file from an input to an output an alter the volume via a factor n.

You first fwrite a header of size 44 bytes to a file output.wav with the help of an array and then the sample files, each two byte sized via a while loop.

What I do not understand is, in the cs50 documentation fopen() is either write or append. How does fwrite() not overwrite the header in the second writing process?

     uint8_t header_arr[HEADER_SIZE];
fread(header_arr, HEADER_SIZE, 1, input);

fwrite(header_arr, HEADER_SIZE, 1, output);

// TODO: Read samples from input file and write updated data to output file
int16_t wav;
while (fread(&wav, sizeof(int16_t), 1, input))
{
    wav = wav * factor;
    fwrite(&wav, sizeof(int16_t), 1, output);
}

Could somebody explain? Thank you!

1 Answer 1

1

First, understand the difference between write and append when opening a file for output.

If you open a file with "w", or write, it will open the file of the specified name. If it doesn't already exists, it simply creates and opens the file. BUT, if a file that already exists is opened for write, the fopen() call will empty the existing file. Any data currently in the file will be lost.

If you open a file with "a" or append, it's a bit different. Again, if the file doesn't exist, a new file is created and opened. If the file does exist, it is opened, but the file pointer's position pointer is set to the end of the file. Any subsequent writes will write the new data to the end of the file. (This assumes that the position pointer hasn't been explicitly manipulated by the code.)

Ultimately, if opened for "w", the position pointer is set to the beginning of the file. If opened for "a", it's set for the end of the file.

Now, let's talk about fwrite(). Any time the fwrite function is called, it will write data out to the file using the file pointer's current position pointer. When the write is executed, the position pointer will then be updated to the end of the data just written.

That all means, for example, if an existing file was opened for "w" and then fwrite() is called to write out a 44 byte header, the file would be opened and emptied by the fopen(...,"w") call, the position set to the beginning of the file, then the subsequent fwrite() call would write the 44 bytes out to the file and set the position pointer to the first byte past the 44 byte header. The next fwrite would start writing data at that point, essentially appending data to the file.

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

1
  • Thank you very much for your explanation, this made it much clearer for me.
    – Karl
    Commented Aug 13, 2022 at 23:04

You must log in to answer this question.

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