I'm reading from an external file values but fscanf wont read it correctly
I have my information in an external .c file in the form [char float int\n char float int\n...]but for some reason using fscanf in a while loop as fscanf(time, "%s %.2f %d\n", temp, tempp, temps); everything is saved in the temp variable so when i try to print it the results are
name: tetris, price: 0.00, sold: 0
name: 9.99, price: 0.00, sold: 0
the saved file looks like this
Tetris 9.99 4
Wormgame 4.50 5
my struct is
struct game {
char *name;
float price;
int sold;
};
function that reads
struct game * open_file(char * tiedosto) {
char* filen = strcat(tiedosto, ".c");
struct game *newarray = malloc(sizeof(struct game));
newarray[0].name = NULL;
FILE* time = fopen(tiedosto, "r");
if (!time) {
return NULL;
}
int characters = 0;
int linechange = 0;
while ((characters = fgetc(time)) != EOF) {
if (characters == '\n') {
linechange++;
}
}
rewind(time);
char temp[100];
float tempp;
int temps;
int i;
for ( i = 0; i < linechange; i++) {
fscanf(time, "%s %.2f %d\n", &temp, &tempp, &temps); // this is where the problem lies
newarray = add_peli(newarray, temp, tempp);
newarray[i].sold = temps;
}
fclose(time);
print_items(newarray, i);
return newarray;
}
and lastly the function that adds the name to the struct
struct game *add_peli(struct game* array, char* nimi, float hinta )
{
int i;
for (i = 0; array[i].name != NULL; i++) {
if (array[i].name != NULL) {
if (strcmp(array[i].name, nimi) == 0) {
printf("Game already exists\n");
return array;
}
}
}
struct game* newarray = realloc(array, sizeof(struct game) * (i + 2));
newarray[i].name = malloc(sizeof(char) * (strlen(nimi)+1));
strcpy(newarray[i].name, nimi);
newarray[i].price = hinta;
newarray[i].sold = 0;
newarray[i + 1].name = NULL;
return newarray;
}
as mentioned it for some reason just returns the right amount of games as in if I insert two games and then save the file it will only return two instances