Home > Software engineering >  Saving data from a file to a struct in c
Saving data from a file to a struct in c

Time:09-30

I have two structs that I have to fill with student data. The data is in the format:

age, name, grade, age, group, turn

and in the header of the file is the number of student in the data.

struct school //school
{
    char group; //A,B,C,D,E,F
    char turn; //Morning, AFTERNOON
};

struct student
{
    char *name; 
    char *grade;
    int age;
    struct school *E;
}student[6];

I tried to save first the data from a text with only the age, name, and grade to see if I could do it:

void get_file(const char* file, int *n){ //n is the amount of students
    FILE* fptr;

    fptr = fopen(file, "r");
    if (fptr == NULL){
        printf( "\n Error \n");
        exit(1);
    }
    char* temp;
    int tam = 0;
    fscanf(fptr, "%d", n); //size of the list of students 
    for(int i= 0; i < *n; i  ){

        fscanf(fptr, "%d,%s,%s", &student.age[i],temp, student[i].grade);
        tam = strlen(temp);
        student[i].name = (char*)malloc(tam * sizeof(char));
        strcpy(student[i].name, temp);
        printf("%s\n", student[i].name);//to see if it's correct the content
    } 
    fclose(fptr);
}

But, student.name store for example "Josh, A " when it should only be "Josh". How can I fix this?

It's for an assignment.

EDIT: My data looks like this

4 //size of list
Josh,A,20,D,M
Amber,B,23,E,M
Kevin,C,22,D,A
Adam,A ,21,C,A

Using the Remy Lebeau's solution, I got this

void get_file(const char* file, int *n){
    *n = 0;

    FILE* fptr = fopen(file, "r");
    if (fptr == NULL){
        printf( "\n Error \n");
        exit(1);
    }

    char name[80];
    char grade[2];

    fscanf(fptr, "%d", n); //size of the list of students 

    for(int i = 0; i < *n; i  ){
        fscanf(fptr, "           
  • Related