如果在同一执行中写入和读取文件,程序将挂起
Program hangs if both written to and read from file in same execution
我希望以下代码将数字 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;
}
我知道我可以简单地用 w+
标志打开它,但我只是想知道为什么它会停止..
您没有 free
文件指针,您 fclose
它。在使用 fopen
打开的文件上调用 free()
是未定义的行为。
我敢肯定,如果您将 free(file)
行替换为 fclose(file)
,您的问题就会得到解决。
我还建议您不要为 my_int
和 calloc
分配内存,如果您仅在该函数中使用它的话。将该内存放在堆栈上可能更好,即 int my_int
而不是 int* my_int = calloc(sizeof(int))
。后者要求您稍后在程序中调用 free()
,而前者则不需要。
使用[ fclose ]关闭文件。
fclose(file);
另外,参考资料说:
All internal buffers associated with the stream are disassociated from
it and flushed:
所以
fflush(file);
这里可以避免。
使用[ free ]释放为指针保留的内存。在你的情况下
free(my_int);
如果放在 return
.
之前会有意义
我希望以下代码将数字 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;
}
我知道我可以简单地用 w+
标志打开它,但我只是想知道为什么它会停止..
您没有 free
文件指针,您 fclose
它。在使用 fopen
打开的文件上调用 free()
是未定义的行为。
我敢肯定,如果您将 free(file)
行替换为 fclose(file)
,您的问题就会得到解决。
我还建议您不要为 my_int
和 calloc
分配内存,如果您仅在该函数中使用它的话。将该内存放在堆栈上可能更好,即 int my_int
而不是 int* my_int = calloc(sizeof(int))
。后者要求您稍后在程序中调用 free()
,而前者则不需要。
使用[ fclose ]关闭文件。
fclose(file);
另外,参考资料说:
All internal buffers associated with the stream are disassociated from it and flushed:
所以
fflush(file);
这里可以避免。
使用[ free ]释放为指针保留的内存。在你的情况下
free(my_int);
如果放在 return
.