#include<stdlib.h>
#include<stdio.h>

#define SIZE 50

typedef struct student {
    char name [SIZE];
    char email [SIZE];
    int number;
} student;

// Fonction pour écrire une structure student dans un fichier (prototype: student* stu, FILE* file)
void write_student (student* stu, FILE* file){
    if(stu == NULL || file == NULL)
    {
        fprintf(stderr, "Error: file or structure ill defined\n");
        exit(EXIT_FAILURE);
    }
    fprintf(file, "%s\n%s\n%d\n", stu->name,
            stu->email, stu->number);
}

// Fonction pour lire une structure student depuis un fichier (prototype: student* stu, FILE* file)
void read_student (student* stu, FILE* file){
    if(stu == NULL || file == NULL)
    {
        fprintf(stderr, "Error: file or structure ill defined\n");
        exit(EXIT_FAILURE);
    }
    
    int result = fscanf(file, "%[^\n]\n%s\n%d\n", stu->name,
            stu->email, &stu->number);

    if (result != 3) {
        if (!feof(file)) { // Si ce n'est pas EOF, c'est une erreur de lecture/format
            fprintf(stderr, "Error: Failed to read 3 student fields from file (fscanf returned %d).\n", result);
            // exit(EXIT_FAILURE); // Optionnel: quitter en cas d'erreur
        } else if (result != EOF) {
             fprintf(stderr, "Warning: End of file reached before reading all student fields (read only %d).\n", result);
        }
    }
}

// Fonction main illustrant l'utilisation de read_student et write_student
int main(void) {
    student stu;
    FILE *f1 = NULL;
    FILE *f2 = NULL;
    
    f1 = fopen ("foor", "r");
    if(f1 == NULL)
    {
        fprintf(stderr, "could not open file 'foor' for reading\n");
        return EXIT_FAILURE;
    }
    
    f2 = fopen ("foow", "w");
    if(f2 == NULL)
    {
        fprintf(stderr, "could not open file 'foow' for writing\n");
        fclose(f1); 
        return EXIT_FAILURE;
    }

    // CORRECTION : L'ordre des arguments est inversé dans le PDF, on le corrige ici.
    // Ordre correct: read_student(pointeur vers student, pointeur vers FILE)
    read_student(&stu, f1); 
    
    // L'ordre était déjà correct dans l'implémentation du PDF: write_student(f2,&stu); 
    // Cependant, pour respecter l'ordre du prototype (stu, file), on utilise:
    write_student(&stu, f2); 
    
    fclose(f1);
    fclose(f2);
    
    printf("Student data read from 'foor' and written to 'foow' successfully.\n");
    return EXIT_SUCCESS;
}