In this piece of code I'm trying to check if a string is already in a list. Now I have to use the fread and fwrite functions to store the information in a binary file. I tried doing something but it doesn't seem to take me anywhere. This is the original code without the fread and fwrite:
if(cont < N)
{
printf("\n");
printf("Enter the club name: ");
gets(club[cont].name);
for(i = 0; i < cont; i++)
{
res_entered = strcmp(club[cont].name, club[i].name);
if(res_entered == 0)
{
do
{
printf("This club is present in the list. Enter another one: \n");
gets(club[cont].name);
res_entered = strcmp(club[cont].name, club[i].name);
}while(res_entered == 0);
}
}
cont++;
}
else
{
printf("Error. Maximum number of clubs \n");
}
Can someone help me to understand how to use fread and fwrite in this particular case, please?
Code with fread and fwrite
if(cont < N)
{
fp = fopen("list.dat", "ab");
printf("\n");
printf("Enter the club name: ");
gets(club[cont].name);
strcpy(club[i].name, club[cont].name);
club[i].points = 0;
club[i].gscored = 0;
club[i].gconceded = 0;
fwrite(&club[i], sizeof(club[i]), 1, fp);
fclose(fp);
for(i = 0; i < cont; i++)
{
fp = fopen("list.dat", "rb");
while( (fread(&club[i], sizeof(club[i]), 1, fp)) == 1)
{
cont++;
}
res_entered = strcmp(club[cont].name, club[i].name);
if(res_entered == 0)
{
do
{
printf("This club is present in the list. Enter another one:
gets(club[cont].name);
res_entered = strcmp(club[cont].name, club[i].name);
}while(res_entered == 0);
}
}
fclose(fp);
}
else
{
printf("Error. Maximum number of clubs \n");
}