tags:

views:

66

answers:

2

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 ?
}
+4  A: 

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.

Ignacio Vazquez-Abrams
+1, this seems correct.
casablanca
@Ignacio: if the buffer size is zero, there's nowhere for `fgets()` to write the terminal null, is there? It can't write beyond the end of the space it is given; if it is given no space, it cannot write.
Jonathan Leffler
+2  A: 

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.

Matthew Flaschen