finesttea
finesttea

Reputation: 29

How can I get one line and other lines in two parts in C?

I try to get input from a text file. First line of the text only contains a number, then others related with it like that;

4
ssss
sss
ss
s

I used fgets function for getting these lines from file, but I want to use "4" and the other lines in different functions.

I was getting both these lines with fgets like that;

    char inp[150];
    int i;
    FILE *fp;

    while(1) {
      if(fgets(inp, 150, fp) == NULL) break;
      printf("%s",inp);
      i++;
    }

I used printf for only see that this code getting all lines or not. It is getting all lines same with input, but when I try to print first line of the input "inp[0]", I expect to print "4", but it prints "s" again.

Therefore, I can't use or get the number which is in the first line. How can I print or use first line independently from others.

By the way, the number and the other lines ,which are related with it, can change with another inputs.

Upvotes: 1

Views: 195

Answers (2)

Muhammet Madraimov
Muhammet Madraimov

Reputation: 117

The problem with your code is that fgets(inp, 150, fp) reads until newline, 149 characters read or EOF. So each timefgets(inp, 150, fp) you store new values in inp. And last value is s.

Try to use fgetc and store character by character in inp.

Upvotes: 0

Pass the file pointer to the functions, and have them attempt to read the lines.
That's a basic parser for you.

Don't forget to:

  1. Do error handling, and properly indicate if a read failed.
  2. Reset the file pointer position in case of failure.
    Store the result of fgetpos at the beginning and restore it with fsetpos

Upvotes: 1

Related Questions