I was solving volume (one of the questions in cs50x). Apparently the code that I wrote, works when the file contents are read in an array and from that array, written into the output file.
When I tried to read the input file contents to the output file, by giving a pointer to the output file, it didn't pop any error, but the output was not working.
Can someone explain how reading from a file to a location (say an array) and reading from one file into another file are different.
THIS IS THE CODE FOR REFERENCE
`// Modifies the volume of an audio file
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
// Number of bytes in .wav header
const int HEADER_SIZE = 44;
int main(int argc, char *argv[])
{
// Check command-line arguments
if (argc != 4)
{
printf("Usage: ./volume input.wav output.wav factor\n");
return 1;
}
// Open files and determine scaling factor
FILE *input = fopen(argv[1], "r");
if (input == NULL)
{
printf("Could not open file.\n");
return 1;
}
FILE *output = fopen(argv[2], "w");
if (output == NULL)
{
printf("Could not open file.\n");
return 1;
}
float factor = atof(argv[3]);
// TODO: Copy header from input file to output file
uint8_t arr[HEADER_SIZE];
fread(arr, sizeof(uint8_t), HEADER_SIZE, input);
fwrite(arr, sizeof(uint8_t), HEADER_SIZE, output);
// creating a temprary location in memory for the content bytes of a wave file
int16_t buffer;
// TODO: Read samples from input file and write updated data to output file
while (fread(&buffer, sizeof(int16_t), 1, input))
{
buffer = (buffer) * factor;
fwrite(&buffer, sizeof(int16_t), 1, output);
}
// Close files
fclose(input);
fclose(output);
}`
But if I wrote the code below, it won't work
` // TODO: Copy header from input file to output file
// reading from the input file to the output file.
fread(output, sizeof(uint8_t), HEADER_SIZE, input);
// creating a temprary location in memory for the content bytes of a wave file
int16_t buffer;
// TODO: Read samples from input file and write updated data to output file
while (fread(&buffer, sizeof(int16_t), 1, input))
{
buffer = (buffer) * factor;
fwrite(&buffer, sizeof(int16_t), 1, output);
}`
Can someone explain how reading from a file to a location (say an array) and reading from one file into another file are different.