Search code examples
ctext-filesbinaryfiles

I can't display from binary file to text file


I need to write a C program that has the structure "contestant" with data about some contestants and the following subprograms:

  1. A subprogram that reads the data about contestants from the keyboard.
  2. A subprogram that writes the data in a binary file.
  3. A subprogram that displays all the contestants and their data in the console.
  4. A subprogram that displays in the text file all the contestants that have a base score of 30, a special score of 50 and obtained "1"(0 and 1 are the only options) for all the 10 tasks.

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);
}


Solution

  • 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);
                }
            }
        }