#include <stdio.h>
#include <stdlib.h>
struct Product{
int code;
char name[50];
float price;
int quantity;
float costPurchase;
};
void readProducts(struct Product products[],int *totalProducts){
FILE *fileReadProduct;
int i=0;
fileReadProduct = fopen("Purchase.txt", "r");
if(fileReadProduct != NULL)
{
while(fscanf(fileReadProduct, "%d %s %f %d %f",&products[i].code,products[i].name,
&products[i].price,&products[i].quantity,&products[i].costPurchase) != EOF){
i++;
}
}
*totalProducts=i;
fclose(fileReadProduct);
}
void saveProducts(struct Product products[],int totalProducts){
FILE * fileSaveProduct;
int i;
fileSaveProduct = fopen("Purchase.txt", "w+");
for(i=0;i<totalProducts;i++){
fprintf(fileSaveProduct, "%d %s %.2f %d %.2f\n", products[i].code,products[i].name,
products[i].price,products[i].quantity, products[i].costPurchase);
}
fclose(fileSaveProduct);
}
int main () {
struct Product products[100];
int ch=0;
int i=0;
int totalProducts=0;
readProducts(products,&totalProducts);
while(ch!=3){
printf("1. Add a new product\n");
printf("2. Display all products\n");
printf("3. Exit\n");
printf("Your choice: ");
scanf("%d",&ch);
if(ch==1){
printf("Enter product code: ");
scanf("%d",&products[totalProducts].code);
fflush(stdin);
printf("Enter product name: ");
gets(products[totalProducts].name);
printf("Enter product price: ");
scanf("%f",&products[totalProducts].price);
printf("Enter product quantity: ");
scanf("%d",&products[totalProducts].quantity);
printf("Enter product cost purchase: ");
scanf("%f",&products[totalProducts].costPurchase);
totalProducts++;
saveProducts(products,totalProducts);
}else if(ch==2){
printf("\n%-15s%-15s%-15s%-15s%-15s\n","Code","Name","Price","Quantity","Cost purchase");
for(i=0;i<totalProducts;i++){
printf("%-15d%-15s%-15.2f%-15d%-15.2f\n",products[i].code,products[i].name,products[i].price,products[i].quantity, products[i].costPurchase);
}
printf("\n");
}else if(ch==3){
//exit
}else{
printf("\nWrong choice.\n");
}
}
return(0);
}
Comments
Leave a comment