所以我创建了一个保存在文件中的数组。我在文件中将数字 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/