C: using fgets() to read from file

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...

Answers


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?


Need Your Help

No cqlsh on Cassandra install on CentOS 7.2

installation cassandra-2.0 centos7 cqlsh

I installed cassandra but I do not see cqlsh. I have anaconda so I installed cqlsh from that

localStorage.length does not work in my code or?

jquery local-storage

I have a basic input text and appended area.I am adding texts dynamically and wanted to count how many dynamic element i added.