Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct{
char code[6];
int year;
char country[26];
} product;
void add();
void display();
void del(int year);
void add()
{
FILE *addPtr;
product p;
char anymore = 'Y';
addPtr = fopen("product.dat","ab");
while(toupper(anymore) == 'Y')
{
printf("Product Code: ");
gets(p.code);
printf("Expired year of the product: ");
scanf("%d",&p.year);
printf("Product country: ");
fflush(stdin);
gets(p.country);
fwrite(&p,sizeof(product),1, addPtr);
printf("Anymore:(Y/N) ?\t");
scanf("%c",&anymore);
fflush(stdin);
}
fclose(addPtr);
system("pause");
system("cls");
}
void display()
{
FILE *disPtr;
product p;
disPtr = fopen("product.dat","rb");
/*
fread(&p,sizeof(product),1, disPtr);
while (!feof(disPtr));
{
printf("Product Code: %s\n",p.code);
printf("Expired year of the product: %d\n",p.year);
printf("Product country: %s\n\n",p.country);
fread(&p,sizeof(product),1, disPtr);
}
*/
while ( (fread(&p,sizeof(product),1, disPtr)) == 1)
{
printf("Product Code: %s\n",p.code);
printf("Expired year of the product: %d\n",p.year);
printf("Product country: %s\n\n",p.country);
}
fclose(disPtr);
system("pause");
system("cls");
}
void del(int year)
{
FILE *delPtr;
FILE *tempPtr;
product p;
delPtr = fopen("product.dat","rb");
tempPtr = fopen("temp.dat","wb");
while(fread(&p,sizeof(product),1,delPtr) == 1)
{
if (year == p.year)
fread(&p,sizeof(product),1,delPtr);
fwrite(&p,sizeof(product),1,tempPtr);
}
fclose(delPtr);
fclose(tempPtr);
system("cls");
}
int main()
{
int menu, year;
do
{
printf("Product Processing System\n");
printf("=========================\n");
printf("1. Add product\n");
printf("2. Display product\n");
printf("3. Delete product\n");
printf("0. Exit\n");
printf("Your choice: ");
scanf("%d", &menu);
fflush(stdin);
system("cls");
switch (menu)
{
case 1:
add();
break;
case 2:
display();
break;
case 3:
printf("Year: ");
scanf("%d",&year);
del(year);
break;
}
}while (menu != 0);
}
Issue: After input year, it cannot delete the record if it is last record in del function.
How to fix this issue?