小编mul*_*c61的帖子

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

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

c fopen fwrite

0
推荐指数
1
解决办法
88
查看次数

标签 统计

c ×1

fopen ×1

fwrite ×1