简体   繁体   中英

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 ?
}

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM