简体   繁体   English

执行fwrite时C程序终止

[英]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 因此,在这段代码中,我想做的是从波形文件中读取最初的44个字节,然后将其放入新文件中,然后使用左右短裤的序列来计算组合

new file : (intial 44bytes - combination - combination - combination...) but it stops when I try to call fwrite. 新文件:(初始44字节-组合-组合-组合...),但是当我尝试调用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: 您忘了测试fopen的失败,例如:

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 ) 并使用调试器( gdb

You just opened write file in "rb" mode. 您刚刚以“ rb”模式打开了写入文件。

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

Please try 请试试

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

and check 并检查

finalFile==NULL

Please open file in Write mode , Like "wb" 请以写入模式打开文件,如“ 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 . 这就是为什么根据fopen手册页会发生此问题的原因。 Please try write mode. 请尝试写入模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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