0

I have a text file that looks like this:

1;Einstein;Albert;3914-1948-4
2;Newton;Isaac;1941-5525-2
...

and a struct like this

typedef struct {
int Nr;
char FName[30];
char LName[30];
char ID[12];
} student;

I have a function that takes a string structured like one line from the file above and a struct and saves the data from the line in the struct.

Now I have to read one line from the file, process it with my function and go to the next line.

I would do it in a loop that would jump from line to line and create a new variable type student for each line.

But I have no idea how to do that. fgets only lets you read in one line and I don't see a way to jump to the next line.

Is there a way to do this that is not too complicated?

user3004619
  • 77
  • 1
  • 2
  • 8

2 Answers2

1

Each call to fgets returns a new line until EOF (i.e. "end of file").

See: fgets

For a bare outline example of a read loop using fgets, see:

fgets - get a string from a stream

However, if you can't be sure of allocating a buffer long enough to hold a line, it is often better to use fgetc to read each character one at a time -- not to worry, the file I/O is still buffered, not read a character at a time -- and assemble the text into tokens as you go along rather than dealing with lines longer than whatever buffer you provide which may then require you to handle tokens split between one filled buffer and the next.

Ned
  • 937
  • 6
  • 10
  • but it says: "Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (aq\0aq) is stored after the last character in the buffer." so it would stop reading after the first line – user3004619 Jan 15 '14 at 05:02
  • Well, EOF is no problem, you're done. But in the case of newline, the next call to `fgets` will read the characters after the newline -- i.e. the next line. – Ned Jan 15 '14 at 05:10
  • 1
    @user3004619 that's for one call..if you call it again, you will get another line and so on until EOF – pinkpanther Jan 15 '14 at 05:12
1

You can do like this :

    str char *str;
    str = fgets(fptr);
    while (str != EOF)
    {
        printf ("%s", str);
        str  = fgets(fptr);
    }
SeeTheC
  • 1,560
  • 12
  • 14