假设我已经创建了一个名为“room.txt”的文件,它包含以下内容:
20 10 5
执行下面的代码后,系统会要求我指定哪个变量将其值减少 1。
例如:如果我输入“1”,它将减少数字“20”
但是,它不会减少该值。
相反,它会删除“room.txt”文件的内容。
当我从程序中输入内容时,如何使其保留文件中的值?
另外,当我在程序中输入“1”“2”“3”时,如何分别减少“20”“10”“5”值? p>
#include<stdio.h>
char rooms[]={"rooms.txt"};
struct rooms {
int stdsuite;
int premsuite;
int deluxesuite;
};
int stdsuite;
int premsuite;
int deluxesuite;
void availablerooms ()
{
FILE*fp;
fp = fopen(rooms,"r");
fscanf(fp,"%d %d %d",&stdsuite,&premsuite,&deluxesuite);
system("cls");
system("cls");
printf("\n\n");
printf("\t\t-----------------------------------------------\n");
printf("\t\t Room Availability\n");
printf("\t\t-----------------------------------------------\n\n");
printf("--------------------------------------------------------------------------------\n\n");
printf("\t\t Standard Suite :\t%d / 20\n\n",stdsuite);
printf("\t\t Premium Suite :\t%d / 10\n\n",premsuite);
printf("\t\t Deluxe Suite :\t%d / 5\n\n",deluxesuite);
printf("--------------------------------------------------------------------------------\n\n");
fflush(stdin);
}
int main ()
{
int choice;
FILE*fp;
availablerooms();
printf("1. Standard Suite\n\n2. Premium Suite\n\n3. Deluxe Suite\n\n");
printf("Please enter the selected room value (1-3): ");
scanf("%d",&choice);
fflush(stdin);
if (choice == 1)
{
fp = fopen(rooms,"w");
stdsuite--;
}
else if (choice == 2)
{
fp = fopen(rooms,"w");
premsuite--;
}
else if (choice == 3)
{
fp = fopen(rooms,"w");
deluxesuite--;
}
else
printf("\nThe input is invalid!");
}
任何帮助将不胜感激! :)
最佳答案
要完成您在标准 C 中尝试执行的操作,您必须:
- 打开文件以读取“r”。
- 将其内容读取到您自己的数据结构中。
- 修改数据结构。
freopen
用于写入“w”的文件。†- 写回修改后的数据结构。
- 关闭文件。
† 这是必要的,因为没有标准的 C 方法可以在“r+”模式下截断文件。
关于c - 修改现有文本文件的值(C 编程语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39897428/