-1

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 ::
franklin
  • 35
  • 7
  • "...it somehow gets messed up." That's way too unspecific. Try to narrow it down. Add debug output. Check intermediate data. Use a debugger. Come up with a [mcve]. – DevSolar Jun 03 '18 at 16:27
  • Hello, I added a snippet of the output. Would you mind taking a look? Thanks – franklin Jun 03 '18 at 16:30
  • Related: [How to read / parse files in C. The FAQ.](https://stackoverflow.com/questions/35178520/how-to-read-parse-input-in-c-the-faq) – DevSolar Jun 03 '18 at 16:34
  • user3121023 Your solution has worked. Thanks you very much. Have a great day – franklin Jun 03 '18 at 16:35

1 Answers1

1

After the third fscanf in the loop, the next character in the file buffer is a newline. On the next iteration of the loop, the fscanf using the %[^\n] format specifier reads nothing since it stops at a newline. This throws of subsequent reads.

You need to consume the newline after the last read in the loop:

fscanf(f1, "%[^\n]", movie[i].title);
fscanf(f1, "%d", &movie[i].year);
fscanf(f1, "%s", movie[i].quality);
fgetc(f1);
dbush
  • 205,898
  • 23
  • 218
  • 273