所以我创建了一个保存在文件中的数组。我在文件中将数字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 [room] = A [room] -1 因此结果将为A [1] = 3,并修改文件中保存的A [1]。
答案 0 :(得分:0)
在行后使用fclose fprintf(output,“%d \ n”,B4 [i]);
答案 1 :(得分:0)
我在您的代码中发现的错误很少,这是您的固定代码:
#define HOME_SIZE 100
void show_rooms(int B[]){
for (int i = 0; i < HOME_SIZE; i++){
if (i % 10 == 0){
printf("\n\n");
}
printf("B-4-%3d(%d) ", i + 1, B[i]);
}
}
void buildingB4()
{
FILE *input, *output;
input = fopen("B4.txt", "r");
unsigned int B[HOME_SIZE], room;
if (input == NULL){
fclose(input);
// Setting all homes to 4.
for (int i = 0; i < HOME_SIZE; ++i){
B[i] = 4;
}
output = fopen("B4.txt", "w");
for(int i = 0; i < HOME_SIZE; ++i)
fprintf(output, "%d\n", B[i]);
fclose(output);
show_rooms(B);
}
else{
for (int i = 0; i < HOME_SIZE; ++i){
fscanf(input, "%d", &B[i]);
}
fclose(input);
show_rooms(B);
printf("\nPlease choose a room:B-4-");
scanf("%d", &room);
if (room > 0 && room <= HOME_SIZE)
B[room - 1] -= 1;
output = fopen("B4.txt", "w");
for(int i = 0; i < HOME_SIZE; ++i)
fprintf(output, "%d\n", B[i]);
}
}
注意:
未来发展的提示: