I need to write a C program that has the structure "contestant" with data about some contestants and the following subprograms:
I managed to do correctly the first 3 subprograms, but it seems I have a problem on the fourth one. I opened the binary file and the text one, then I tried reading contestants from the file until there are no more contestants and see if the base score is 30, special score 50, and "1" for all the 10 tasks and if so, I tried to display the name of each contestant that respects this conditions in a file named "raport.txt", but I don't have any output. Here is my struct and my fourth subprogram:
typedef struct contestants {
int marca;
char special;
char name[30];
int category;
char basepoints;
char elem[10];
};
void raport()
{
FILE* f;
FILE* g;
fopen_s(&g, "raport.txt", "w");
fopen_s(&f, "contestants.dat", "rb");
contestants a;
while (fread(&a, sizeof(contestants), 1, f) == 1)
{
int ok = 1;
if (a.marca != 0 && a.basepoints == 30 && a.special == 50)
{
for (int i = 0; i < 10; i++)
{
if (a.elem[i] == 0)
{
ok = 0;
break;
}
}
}
if (ok == 1)
{
fprintf_s(g, "%s\n", a.name);
}
}
fclose(f);
fclose(g);
}
If the base score or special values don't match the requirements, you skip the loop that checks the elem
array, so ok
is still set to 1
. So it prints the record in that case.
You should move the if (ok == 1)
code inside the first if
block.
while (fread(&a, sizeof(contestants), 1, f) == 1)
{
if (a.marca != 0 && a.basepoints == 30 && a.special == 50)
{
int ok = 1;
for (int i = 0; i < 10; i++)
{
if (a.elem[i] == 0)
{
ok = 0;
break;
}
}
if (ok == 1)
{
fprintf_s(g, "%s\n", a.name);
}
}
}