Opening, Reading and Updating a text file.
Hi guys,
I have a slight problem on how can I read from a text file in order to use the stored data. Later on if a purchase is made I would like the 'Amount of Money' which is stored in the text file to be updated together with the 'Number of Bees'.
This is what is stored in the text file:
Total number of Bees: 15
Total number of Infected Bees: 5
Total amount of Money: 1500
Total amount of Honey Jars: 65
Total amount of Beeswax: 0
Below is the program I have written which requires the above data:
Code:
#include<stdio.h>
#include <iostream>
int main()
{
int numofbees;
float price = 5;
char query;
printf("How many bees would you like to purchase?\n");
scanf("%d", &numofbees);
printf("That will be $%f, confirm? (Y/N)\n", price*numofbees);
scanf(" %c", &query);
if(query == 'y'|| query == 'Y') {
printf("Transaction completed.");
}
else {
printf("Transaction cancelled.");
}
getchar();
getchar();
return 0;
}
The following is a piece of code I have written in order to open the file:
Code:
#include <stdio.h>
#define MAX 20
char string[20];
int main()
{
FILE *f;
int x;
f=fopen("Inventory.txt","r");
if (!f)
{ printf("Couldn't open file. Please try again.\n");
return 1;
}
while(fgets(string, 20, f))
{
printf("%s", string);
}
fclose(f);
getchar();
getchar();
return 0;
}
Overall, my question is how can I read from a text file in order to use the data and later on to update the text file itself.
Any help or tips would be greatly appreciated.