Please take a look my code below.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct noun
{
char singular[80];
char plural[80];
};
struct noun p;
struct noun r;
void pluralize(struct noun *p);
void addNouns(struct noun *p);
void read();
int main(void)
{
char choice;
do {
pluralize(&p);
addNouns(&p);
do {
flushall();
printf("More nouns? ");
scanf("%c", &choice);
choice = toupper(choice);
printf("\n");
} while(choice != 'Y' && choice != 'N');
} while (choice != 'N');
printf("\n");
read();
}
void pluralize(struct noun *p)
{
int x;
printf("Please input singular: ");
scanf("%s", &p->singular);
// Store singular to plural
strcpy(p->plural, p->singular);
x = strlen(p->plural);
// x-1 = Last character
// x-2 = Before last character
if(p->plural[x-1] == 'y') // y
{
strcpy(&p->plural[x-1], "ies");
}
else if(p->plural[x-1] == 's') // s
{
strcat(p->plural, "es");
}
else if(p->plural[x-2] == 'c' && p->plural[x-1] == 'h') // ch
{
strcat(p->plural, "es");
}
else if(p->plural[x-2] == 's' && p->plural[x-1] == 'h') // sh
{
strcat(p->plural, "es");
}
else if(p->plural[x-1] == 'x') // x
{
strcat(p->plural, "es");
}
else
{
strcat(p->plural, "s");
}
printf("\nPluralize Section");
printf("\n=======================");
printf("\nSingular: %s", p->singular);
printf("\nPlural: %s\n\n", p->plural);
}
void addNouns(struct noun *p)
{
FILE *add, *read;
read = fopen("nouns.dat", "rb");
if(read == NULL)
{
add = fopen("nouns.dat", "a+b");
fwrite(p, sizeof(struct noun), 1, add);
}
else
{
fread(&r, sizeof(struct noun), 1, read);
while (!feof(read))
{
if (strcmp(r.singular, p->singular)==0)
{
printf("Record exist.");
exit(0);
}
else
{
add = fopen("nouns.dat", "a+b");
fwrite(p, sizeof(struct noun), 1, add);
fclose(add);
}
fread(&r, sizeof(struct noun), 1, read);
}
}
}
void read()
{
FILE *fp;
fp = fopen("nouns.dat", "rb");
if(fp == NULL)
{
printf("\nError.");
}
else
{
fread(&p, sizeof(struct noun), 1, fp);
while (!feof(fp))
{
printf("Singular: %s\n", p.singular);
printf("Plural: %s\n", p.plural);
fread(&p, sizeof(struct noun), 1, fp);
}
}
}
My problem is the "record exist" message. My programs will compare the content in the binary with the user input. If user input a string which has been append into the binary before. It will tell user record exist then stop the program. But now the "record exist" message will continue display even user input a string which was not contain in the binary files so...