I'm having a problem with some code in my program. I need to read a file and put it's content line by line into a struct. The file is about 800 lines long, and when i try to print my struct, which should now contain the content of the file, it only print about 30 of the lines as they should be. The rest is filed with error or wrong formatting. This is my function as it is now, and i simply call it in main. I am not sure what is wrong but maybe it has something to do with my malloc call?
void read_file(void){
int lines = count_lines(); /*function to count amount of lines in file*/
FILE *file;
int i = 0;
char filename[] = "race.txt";
file = fopen(filename, "r");
race_info *race = malloc(sizeof(race_info));
if (file != NULL) {
while (i < lines) {
fscanf(file, " %[A-Za-z]s %[A-Za-z]s %[A-Z]s %d %[A-Z]s %[A-Z]s %d %d",
race[i].race_name,
race[i].name,
race[i].lastname,
&race[i].age,
race[i].team,
race[i].country,
&race[i].position,
&race[i].time);
i++;
}
}
else {
perror(filename); //print the error message
}
for (i = 0; i < lines; i++) {
printf("%s %s %s %d %s %s %d %d",
race[i].race_name,
race[i].name,
race[i].lastname,
race[i].age,
race[i].team,
race[i].country,
race[i].position,
race[i].time);
}
fclose(file);
}
The struct is setup as following:
#define MAX_CHAR 100
struct race_info{
char race_name[MAX_CHAR];
char name[MAX_CHAR];
char lastname[MAX_CHAR];
int age;
char team[MAX_CHAR];
char country[MAX_CHAR];
int position;
int time;
};
typedef struct race_info race_info;
The lines from the file is setup as:
RaceName "Name LASTNAME" AGE TEAM Country Position TIME
The goal is to print the struct so that all 800 lines are printed with the same formatting as the file. But when printed it does only prints about 200 lines and and it does not go from start of file to the end, but takes content from the middle of it. A lot of the lines also have wrong formatting.