Andreea Elena
Andreea Elena

Reputation: 145

How to fix writing a text file based on a binary file

I am creating a text file based on a binary file , reading the records from the binary file and writing them in the text file. The first subprogram is the creation of the binary file and the second for creating the text file.

#include<stdio.h>
typedef struct {
    char CNP[14];
    char nume[30];
    int an;
    int grupa;
    int nrDisc;
    int note[20];
}STUDENT;

void creare(char*nume) {
    FILE*f;
    STUDENT s;
    fopen_s(&f, nume, "wb");
    if (!f)
        printf("Eroare");
    else {
        printf("CNP:");
        gets(s.CNP);
        while (!feof(stdin)){
            printf("Nume:");
            gets(s.nume);
            printf("An:");
            scanf_s("%d", &s.an);
            printf("Grupa:");
            scanf_s("%d", &s.grupa);
            printf("Nr. discipline:");
            scanf_s("%d", &s.nrDisc);
            for (int i = 0; i < s.nrDisc; i++)
            {
                printf("Nota[%d] este:", i);
                scanf_s("%d", &s.note[i]);
            }
            fwrite(&s, sizeof(s), 1, f);
            getchar();
            printf("CNP:");
            gets(s.CNP);
        }
        fclose(f);
    }
}


void raport(char*nume_binar, char*nume_text) {
    FILE*f;
    fopen_s(&f, nume_binar, "rb");
    if (!f)
        printf("Eroare");
    else {
        FILE*g;
        STUDENT s;
        fopen_s(&g, nume_text, "w");
        while (fread(&s, sizeof(s), 1, f)==sizeof(s));
         {          
            fprintf(g,"%s   %s  %d  %d  %d\n ", s.CNP, s.nume, s.an, s.grupa, s.nrDisc);
            for (int i = 0; i < s.nrDisc; i++)
            {
                fprintf(g, "Nota %d este:", i);
                fprintf(g, "%d\n", s.note[i]);
            }

        }

        fclose(g);

    }
    fclose(f);
}




void main() {
    char nume_fisier[] = "Student.dat";
    char nume_fisier_txt[] = "Raport.txt";
    //creare(nume_fisier);
    raport(nume_fisier, nume_fisier_txt);
}

For example , I am writing 2 records in the binary file, but only the last record appears in the text file.

Upvotes: 0

Views: 54

Answers (1)

Nevus
Nevus

Reputation: 1416

while (fread(&s, sizeof(s), 1, f)==sizeof(s));

You have an extra semicolon ';' here. It leads to while loop running continuously until it reaches end of file that is structure s contains last structure. It means that

{          
            fprintf(g,"%s   %s  %d  %d  %d\n ", s.CNP, s.nume, s.an, s.grupa, s.nrDisc);
            for (int i = 0; i < s.nrDisc; i++)
            {
                fprintf(g, "Nota %d este:", i);
                fprintf(g, "%d\n", s.note[i]);
            }

        }

this block writing to text file runs only once and for last structure of binary file. Also note that fread returns number of elements read not size of elements read so that statement should be while(fread(&s, sizeof(s), 1, f) == 1) {...}

Upvotes: 2

Related Questions