[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: [OT] Help with glibc memory streams



Package: libc6
Severity: important

> Would you now please accept that there absolutely _has_ to be an
> end-of-line character at the end of the last line in a file so that
> fgets does not return NULL when reading the last line?

No, no no.

from fgets(3):

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


and from fmemopen(3) info:

     For a stream open for reading, null characters (zero bytes) in the
     buffer do not count as "end of file".  Read operations indicate
     end of file only when the file position advances past SIZE bytes.
     So, if you want to read characters from a null-terminated string,
     you should supply the length of the string as the SIZE argument.

and from fgets(3) info:

     *Warning:*  If the input data has a null character, you can't tell.
     So don't use `fgets' unless you know the data cannot contain a
     null.  Don't use it to read files edited by the user because, if
     the user inserts a null character, you should either handle it
     properly or print a clear error message.  We recommend using
     `getline' instead of `fgets'.

This could be a problem, but not in this case (just some info).

Yours only works becuase it implicitly causes fgets() to stop reading.
That is a hack and shouldn't be needed ("\n" is not EOF).

This is, IMO, a legitimate bug. Note, I also tested this same problem with
fgetc() and it worked perfectly, so this is a problem in fgets.

#include <stdio.h>

int main()
{
   char *str = "test";
   char line[80];
   FILE *stream;

   stream = (FILE *)fmemopen(str, strlen(str), "r");

   while (fgets(line, sizeof(line), stream) != NULL)
      fputs(line, stdin);

   perror("fgets");
   printf("%s", line);

   fclose(stream);

   exit(0);
}

-- 
 -----------=======-=-======-=========-----------=====------------=-=------
/  Ben Collins  --  ...on that fantastic voyage...  --  Debian GNU/Linux   \
`  bcollins@debian.org  --  bcollins@openldap.org  --  bcollins@linux.com  '
 `---=========------=======-------------=-=-----=-===-======-------=--=---'



Reply to: