C: using fgets() to read from file

185 views Asked by At

I currently have this>

FILE *in=fopen("some_file.txt", "r");
char input[3];
int i=0, j=0;

if(in!=NULL) {
  fgets(input, sizeof(input), in);
  initialize(input);
}

  while(j<100) {
    fgets(input, sizeof(input), in);
    addNode(head,input);
    j++;
  }
fclose(in);

display();

I think I have a problem with fgets(). In my mind, three chars are> input[0] = some char, input[1] = '\0', input[2] = not_important.

And, this looks ok, but, in my file there are a couple of elements that contain 2 charachters.. And that is where the problems start. I believe that this input should work:

input[0] = some char, input[1] = 'some_char', input[2] = '\0'. But, it doesn't...

Input file>

A B C D E

Q W E R Ty

Z X C V B

My output:

Data 1: A

Data 2: B

Data 3: C

Data 4: D

Data 5: E

Data 6: Q

Data 7: W

Data 8: E

Data 9: R

Data 10: Ty

Data 11:

Data 12: Z

Data 13: X and then it goes back to "normal"

So, one element is added that should not be there... It is added after the element that has two chars. That element is also at the end of the line, but I don't believe that has anything to do with it.

Any ideas?

I just tested it, and the element with two chars looks like this:

input[0]='Y' input[1]='u' input[2]='\0'

Just as I imagined it would be... But still, a Node is created...

Another test: Next element, after this one, also has input[0]=some_char as it should...

1

There are 1 answers

1
David Schwartz On BEST ANSWER

As the docs say, fgets reads up to a newline, but at most one less than size characters. If that reads everything up to, but not including, a newline, the next read will read that newline and stop.

So each read will read up to two characters, unless stopped by a newline. Your reads are A<space>, B<space>, C<space>, D<space>, E<newline>, Q<space>, W<space>, E<space>, R<space>, Ty, <newline>, Z<space>, ...

Why would you expect anything else?