Chun Chun - 2 months ago 7
C Question

Modifying values of existing text file (C Programming Language)

Let's say I have a file name already created named "room.txt" and it contains the following:


20 10 5


Once I execute the code below, I will be asked to specify which variable to decrease its value by 1.

For example: If I input "1" it will reduce the number "20" in "room.txt".

However, it doesn't reduce the value.

Instead, it deletes the contents of "room.txt" file.

How do I make it so that it retains the values in the file when I enter my input from the program?

Also, how do I reduce the values '20' '10' '5' respectively when I input '1' '2' '3' in my program?

#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!");
}


Any help would be greatly appreciated! :)

Answer

availablerooms should fclose(fp) before returning. And fflush(stdout) instead of stdin.

Then, when trying to write the data back, you only fopen the file, but you don't write anything to it. There you have a major misconception of how the things work. in the 3 ifs, you decrement the relevant variables. But that are purely in-memory operations. opening the file before, doesn't change that. So, remove the three fopens and put a new one after the last if statement followed by a fprintf(fp, "%d %d %d", stdsuite, premsuite, deluxesuite); to do the actual writing. then finish with an fclose(fp) again