Anonym
Anonym

Reputation: 7725

Can fgets ever read an empty string?

Assuming the FILE* is valid, consider:

char buf[128];

if(fgets(buf,sizeof buf,myFile) != NULL) {
   strlen(buf) == 0; //can this ever be true ? In what cases ?
}

Upvotes: 2

Views: 2551

Answers (2)

Matthew Flaschen
Matthew Flaschen

Reputation: 284826

Yes. Besides passing 1 (as noted by Ignacio), fgets doesn't do any special handling for embedded nulls. So if the next character in the FILE * is NUL, strlen will be 0. This is one of the reasons why I prefer the POSIX getline function. It returns the number of characters read so embedded nulls are not a problem.

Upvotes: 4

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

From the fgets(3) man page:

DESCRIPTION

  fgets() reads in at most one less than size characters from stream  and
  stores  them  into  the buffer pointed to by s.  Reading stops after an
  EOF or a newline.  If a newline is read, it is stored into the  buffer.
  A '\0' is stored after the last character in the buffer.

...

RETURN VALUE

...

  gets() and fgets() return s on success, and NULL on error or  when end
  of file occurs while no characters have been read.

From that, it can be inferred that a size of 1 will cause it to read an empty string. Experimentation here confirms that.

Incidentally, a size of 0 appears to not modify the buffer at all, not even putting in a \0.

Upvotes: 4

Related Questions