Do not append if found in the binary file?
First, please view 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);
int 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);
}
int addNouns(struct noun *p)
{
FILE *fp;
int ret;
fp = fopen("nouns.dat", "a");
fread(&r, sizeof(struct noun), 1, fp);
while (!feof(fp))
{
if (p->singular == r.singular)
{
printf("\nRepeat.");
exit(0);
}
else
{
ret = fwrite(p, sizeof(struct noun), 1, fp);
fclose(fp);
break;
}
fread(&r, sizeof(struct noun), 1, fp);
}
return ret;
}
void read()
{
FILE *fp;
fp = fopen("nouns.dat", "r");
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);
}
}
}
I can read my binary files correctly but I can't identified the content of binary files correctly. For example, If user input "father", the binary files will have "father" and "fathers". Now is the main problem...if user key in "father" again. My program should tell user singular has repeat then I should not append this "father" into my binary files again. So far I has make some change in the addNouns function but I still can't detect if the record is repeat or non- repeat. So please help. Very thanks you.