c - 如果在同一执行中写入和读取文件,程序将挂起

标签 c fopen fwrite

我希望以下代码将数字 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+ 标志打开它,但我只是想知道它为什么会停止......

最佳答案

你不是释放一个文件指针,而是fclose它。在使用 fopen 打开的文件上调用 free() 是未定义的行为。

我敢肯定,如果您将 free(file) 行替换为 fclose(file),您的问题就会得到解决。


我还建议您不要为 my_intcalloc 分配内存,如果您仅在该函数中使用它的话。将该内存放在堆栈上可能更好,即 int my_int 而不是 int* my_int = calloc(sizeof(int))。后者要求您稍后在程序中调用 free(),而前者则不需要。

关于c - 如果在同一执行中写入和读取文件,程序将挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38515708/

相关文章:

c - fwrite() 将未知的零

c - fwrite() 阻止调用并且不写入文件

c - xmlNewChild并不总是写入元素的值

java - Tizen Mobile 和 iPad Linux - 它是否允许 GCC 和 Java?

c - 如何为 `system()` 调用的命令提供参数?

c - 为什么 fopen 不打开现有文件? (返回 NULL,错误号 ENOENT)

C++ 制作特定大小的文件

c - 没有不必要执行的可读条件逻辑?

c++ - fopen ("filename", "wb") 返回 null

c - 如何将 for 循环中的整数作为十六进制值输出到文件