Newsgroups: comp.unix.programmer Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!think.com!mintaka!bloom-picayune.mit.edu!news From: scs@adam.mit.edu (Steve Summit) Subject: Re: sscanf always generates error condition Message-ID: <1991May7.020259.3646@athena.mit.edu> Sender: news@athena.mit.edu (News system) Reply-To: scs@adam.mit.edu Organization: Thermal Technologies, Cambridge, MA References: <1991Apr30.233554.1321@agate.berkeley.edu> <1991May1.024357.7750@dg-rtp.dg.com> Distribution: usa Date: Tue, 7 May 91 02:02:59 GMT Lines: 42 In article <1991May1.024357.7750@dg-rtp.dg.com> hunt@dg-rtp.rtp.dg.com writes: >In article <1991Apr30.233554.1321@agate.berkeley.edu>, ilan343@violet.berkeley.edu (Geraldo Veiga) writes: >> System error: Bad file number >> (This message corresponds to errno=9) > >In the test case, errno is being used without having a value assigned to >it, so the "9" is just garbage that happened to be in the memory >associated with errno at the time. Actually, "Bad file number" is an extremely likely inadvertent errno value after a successful call to sscanf, and not because of any random memory contents. sscanf (and, equivalently, sprintf) work by setting up a temporary buffered file descriptor (FILE *) which uses as its I/O buffer the user's string. When the string is exhausted, the stdio code typically falls into the same buffer refilling code (often an internal routine called _filbuf) which attempts to read more data from the associated file into the buffer. The low- level file descriptor for a string pseudo-file is usually set to -1, so the read fails, with EBADF. (This error ends up looking like EOF, which is what we'd want to happen at the end of the sscanf string anyway. Actually, ferror() would probably report that an error had occurred, except that by the time sscanf has returned, the temporary FILE *, and its error indication, has disappeared.) BSD systems (and probably many others) set the internal _IOSTRG flag on string pseudo-files, which can be used to avoid an inadvertent read or write to a bad file descriptor in these cases. As has been (correctly) pointed out, however, it's not incorrect for ISC's sscanf to be leaving EBADF in errno, because (to quote from an old version of the comp.lang.c frequently-asked questions list), "it is only meaningful for a program to inspect the contents of errno after an error has occurred (that is, after a library function that sets errno on error has returned an error code)." (The more common guise under which this issue comes up is "Why does errno contain ENOTTY after a call to printf?") Steve Summit scs@adam.mit.edu