-1
#include<stdio.h>
#include<conio.h>

typedef struct {
      char CNP[14];
      char nume[30];
      int an;
      int grupa;
      int nrDiscipline;
      char note[20];
} STUDENT;

void main() {
    FILE*f;
    char numef[20];
    STUDENT s;
    printf("Nume fisier:"); gets(numef);
    f = fopen(numef, "rb");
    if (!f)
        printf("eroare");
    else {
        FILE*g;
        fopen_s(&g,"stud.txt", "w");
        fread(&s, sizeof(STUDENT), 1, f);
        while (!feof(f)) {
            fprintf( g,"%s %s %d %d %d ", s.CNP, s.nume, s.an, s.grupa, s.nrDiscipline);
            for (int i = 0; i < s.nrDiscipline; i++)
            {
                fprintf(g, "%s", s.note[i]);   
            }

            fread(&s, sizeof(STUDENT), 1, f);
        }
        fclose(g); fclose(f);

    }

}

First I created the binary file, which went good, but then I open the text file and the array is not correct, it appears to contain some random numbers, probably some addresses. I tried everything but it doesn't work.

gudok
  • 4,029
  • 2
  • 20
  • 30
Andreea Elena
  • 135
  • 1
  • 8

1 Answers1

1

Replace

   fread(&s, sizeof(STUDENT), 1, f);
   while (!feof(f)) {
       ...
       fread(&s, sizeof(STUDENT), 1, f);
   }

by

    while (fread(&s, sizeof(STUDENT), 1, f) == sizeof(STUDENT)) {
        ...
    }

this have several advantages :

  • as already mentioned in a remark that allows you to detect the end of the file, contrarily with feof ( Why is “while (!feof(file))” always wrong? )
  • you detect if your file is corrupted (too short)
  • you write only one time the call to fread in your code

Probably modify fprintf(g, "%s", s.note[i]); to be fprintf(g, "%s ", s.note[i]); to separate the notes, and except if you really want to write a very long line add a fputc('\n', g); at the end of the while

bruno
  • 32,421
  • 7
  • 25
  • 37