I'm writing a program to reverse wav files in c. I've (seemingly) finished it and looked over it many times to find any logical errors. It compiles into an executable program, and outputs a wav file. But the output file in corrupted/incorrect somewhere and will not play audio. Do y'all see any problems with it? Thank you.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wav.h"
int check_format(WAVHEADER header);
int get_block_size(WAVHEADER header);
int main(int argc, char *argv[])
{
// Ensure proper usage
if (argc != 3)
{
printf("usage: ./reverse input.wav output.wav\n");
return 1;
}
// Open input file for reading
char *input_name = argv[1];
char *output_name = argv[2];
FILE *inptr = fopen(input_name, "r");
if (inptr == NULL)
{
printf("File could not be opened\n");
return 1;
}
// Read header
WAVHEADER in_wav_header;
fread(&in_wav_header, sizeof(WAVHEADER), 1, inptr);
// check if input file is WAV file
if (check_format(in_wav_header) != 0)
{
fclose(inptr);
printf("unsupported file format\n");
return 1;
}
// Open output file for writing
FILE *outptr;
outptr = fopen(output_name, "w");
if (outptr == NULL)
{
printf("error creating output file\n");
return 1;
}
// Write header to file
fwrite(&in_wav_header, sizeof(WAVHEADER), 1, inptr);
// Use get_block_size to calculate size of block
int block_size = get_block_size(in_wav_header);
printf("%i\n", block_size);
// declare buffer array
BYTE *buffer = malloc(sizeof(block_size));
// set cursor to start of last block of input audio file
fseek(inptr, -block_size, SEEK_END);
// iterate through input file blocks, checking for header, and writing blocks
// to the output file
while (ftell(inptr) >= sizeof(WAVHEADER))
{
fread(buffer, block_size, 1, inptr);
fwrite(buffer, block_size, 1, outptr);
if (fseek(inptr, 2 * -block_size, SEEK_CUR))
{
return 1;
}
}
// close files & free malloc space
free(buffer);
fclose(inptr);
fclose(outptr);
}
int check_format(WAVHEADER header)
{
char check[] = {'W', 'A', 'V', 'E'};
for (int i = 0; i < 4; i++)
{
if (header.format[i] != check[i])
{
return 1;
}
}
return 0;
}
int get_block_size(WAVHEADER header)
{
if (header.numChannels == 1 || header.numChannels == 2)
{
int block_size = (header.bitsPerSample / 8) * header.numChannels;
return block_size;
}
else
{
printf("error: too many audio channels\n");
return 1;
}
}