this is a very noob question. I apologize, but I can´t get it to work.
I have a text file with the layout:
movie a
2000
720p
movie b
2002
1080p
movie c
2004
480p
And my code looks like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SOURCE "test.txt"
#define S 50
typedef struct Movie
{
char title[50];
int year;
char quality[7];
}Movie;
int main (void)
{
FILE *f1;
int i = 0;
char buf[3];
int temp;
Movie *movie = NULL;
movie = (Movie*)malloc(sizeof(Movie));
if ((f1 = fopen(SOURCE, "r")) == NULL)
{
perror ("src error!");
printf ("exiting!");
exit (1);
}
while (1)
{
movie = (Movie*)realloc(movie, ((i+1)*sizeof(Movie)));
if (!movie)
{
perror ("mem error");
exit (1);
}
//fgets(movie[i].title, S, f1);
// fscanf(f1, "%s", buf);
// printf("%s", buf);
fscanf(f1, "%[^\n]", movie[i].title);
fscanf(f1, "%d", &movie[i].year);
fscanf(f1, "%s", movie[i].quality);
i++;
if (feof(f1))
break;
}
fclose(f1);
int j=0;
for (;j<=i;j++)
{
printf ("%d :: %s\n ",j, movie[j].title);
printf ("%d :: %d\n ",j, movie[j].year);
printf ("%d :: %s\n\n ",j, movie[j].quality);
}
return 0;
}
There is a problem with the reading from the file into the structure When executing the program it somehow gets messed up, it stores the lines to wrong variables and etc. I´ve tried reading the lines with fgets, and I can´t figure it out. Any help is appreciated. Thanks
EDIT: This is the output it produces. Seems like a really straightforward and simple program. What am I doing wrong? Thanks
0 :: movie a
0 :: 2000
0 :: 720p
1 ::
1 :: 0
1 :: movie
2 :: b
2 :: 2002
2 :: 1080p
3 ::
3 :: 0
3 :: movie
4 :: c
4 :: 2004
4 :: 480p
5 ::
5 :: 0
5 ::