c - 如何将修改后的数组保存到文件中

标签 c arrays

所以我创建了一个保存在文件中的数组。我在文件中将数字 4 打印了 100 次。现在,每次访问数组中的元素时,该值都会减 1。因此,如果访问 A[1] = 4,则它将变为 A[1] = 3 并保存在文件中。问题是我无法将修改后的数组保存到文件中。

我已经尝试移动 FILE 指针的位置。

void buildingB4()
{
    system("CLS");
    FILE *input, *output;
    int i, B4[100], room;

    input = fopen("B4.txt", "r");
    if (input == NULL)
    {
        output = fopen("B4.txt", "w");
        for (i = 1; i <= 100; i++)
        {
            B4[i] = 4;
            fprintf(output, "%d\n", B4[i]);
        }
        fclose(output);
        for (i = 1; i <= 100; i++)
        {
            if (i % 10 == 0)
            {
                printf("\n\n");
            }
            printf("B-4-%d(%d)\t", i, B4[i]);
        }
    }
    else
    {

        for (i = 1; i <= 100; i++)
        {
            fscanf(input, "%d\n", &B4[i]);
            if (i % 10 == 0)
            {
                printf("\n\n");
            }
            printf("B-4-%d(%d)\t", i, B4[i]);
        }
        fclose(input);
        printf("\nPlease choose a room:B-4-");
        scanf("%d", &room);
        B4[room] = B4[room] - 1;
        output = fopen("B4.txt", "a");
        fprintf(output, "%d\n", B4[i]);
        studentDetails();
    }
}

假设 A[1] = 4 当用户输入为 1 时,1 被保存在名为 room 的变量中。 所以 A[房间] = A[房间] -1 所以结果将是 A[1] = 3 并且它修改了保存在文件中的 A[1]。

最佳答案

在行后使用 fclose fprintf(输出, "%d\n", B4[i]);

关于c - 如何将修改后的数组保存到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56409032/

相关文章:

c - 如何使用 system() 而不是 rename() 在 C 中重命名文件

c - 在 Linux 模块中包含自定义 header

c - 输入int到文件方向

javascript - 根据父数组位置获取最后一个存在的子数组

linux - Bash 'while read line' 到一个数组和总和

arrays - 结构体数组 : How to save in coredata?

c - 为什么在变量完成相同的工作时使用宏?用C语言?

c++ - 想要为 Windows 8.1 安装 Eclipse for c/c++

ios - 查找函数是否已完成循环 firebase

php - 将json字符串的某些值转换为php中的整数