我希望以下代码将数字42写入二进制文件,然后读取并打印出确切的值.它会这样做,但它不会退出,只是停止在等待用户输入时.这是执行我解释的代码:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char argv[]){
char *filename = "test.db";
int *my_int = calloc(1, sizeof(int));
*my_int = 42;
// First we open file to write to it
FILE *file = fopen(filename, "w");
fwrite(my_int, sizeof(int), 1, file);
fflush(file);
free(file);
// Then we want to read from it
*my_int = -1;
file = fopen(filename, "r");
fread(my_int, sizeof(int), 1, file);
free(file);
printf("Read back %d\n", *my_int);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以简单地用w+旗帜打开它,但我只是想知道为什么它只是停止..
你没有free文件指针fclose.调用free()打开的文件fopen是未定义的行为.
我敢肯定,如果你更换你的free(file)线路fclose(file),你的问题将得到解决.
我还建议你不要打扰分配内存my_int使用calloc,如果你使用它仅在该功能.将该内存放在堆栈上可能更好,即int my_int代替int* my_int = calloc(sizeof(int)).后者要求你free()稍后在程序中调用,而前者则不需要.