简体   繁体   中英

C program terminates when doing fwrite

So in this code what im trying to do is read the initial 44 bytes from a wave file put to a new file then calculate combination by using a sequence of left-right shorts

new file : (intial 44bytes - combination - combination - combination...) but it stops when I try to call fwrite.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    FILE * firstFile;
    FILE * finalFile;
    size_t size;
    char *buffer;
    short left;
    short right;
    short combination;
    int loop;

    printf("%s", argv[1]);
    if ((firstFile = fopen("test.wav", "rb")) == NULL) {
        printf("File error");
        exit(1);
    }

    fseek(firstFile, 0, SEEK_END);

    size = ftell(firstFile);

    fseek(firstFile, 0, SEEK_SET);

    buffer = malloc(44);
    fread(buffer, 1, 44, firstFile);

    finalFile = fopen("new.wav", "rb");
    fwrite(&buffer, sizeof(buffer), 1, finalFile);
    loop = 1;

    while (loop == 1) {
        fread(&left, sizeof(short), 1, firstFile);
        if (fread(&right, sizeof(short), 1, firstFile) == 0) {
            loop = 0;
        }

        combination = (left - right) / 2;
        fwrite(&combination, sizeof(short), 1, finalFile);
    }

    fclose(firstFile);
    fclose(finalFile);
    free(buffer);

    return 0;
}

You forgot to test the failure of fopen like:

finalFile = fopen("new.wav", "wb");
if (!finalFile) { perror("new.wav"); exit(EXIT_FAILURE); }

And if you write a file, open it in write mode.

You should of course compile with all warnings & debug info:

gcc -Wall -Wextra -g yoursource.c -o yourbinary

and use the debugger ( gdb )

You just opened write file in "rb" mode.

finalFile = fopen("new.wav", "rb");

Please try

finalFile = fopen("new.wav", "wb");

and check

finalFile==NULL

Please open file in Write mode , Like "wb"

finalFile = fopen("new.wav", "wb");

then you have to check the return values

You opened file in read mode. That's why this issue happened, per the man page of fopen . Please try write mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM