Answer to Question #216141 in C for Snowball

Question #216141
The file named called Purchase.txt contains product details such as item code, product name, price, quantity and cost of purchase. Write a C program to create a file to store the details of Purchase.txt (Use fscanf() and fprintf() functions).
1
Expert's answer
2021-07-11T14:38:16-0400
#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);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS