Sscanf.c



  • I'll bet many of you remember the post about formatting strings using temporary files.

    Probably many of you read the post about misusing sprintf for simple concatenation.

    I'm wondering how many of you took time to look at VS 2003 implementation of sscanf [and many different functions!] found in C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\crt\src\sscanf.c

    The code style of this file is a Gem. At least four functions are declared and defined in the same place using various combinations of defines to achieve different results.

    But that's only the syntax. The true WTF are:

    1. using strlen to determine the size of the buffer (wasting additional O(n) time even if you want to read only one character)

    2. creation of fake temporary file

    <FONT color=#008000 size=2>

    /***

    *int sscanf(string, format, ...) - read formatted data from string

    *

    *Purpose:

    * Reads formatted data from string into arguments. _input does the real

    * work here. Sets up a FILE so file i/o operations can be used, makes

    * string look like a huge buffer to it, but _filbuf will refuse to refill

    * it if it is exhausted.

     

    </FONT>


  • Definitely not the optimum way to do it.  But no so bad, it doesnt make a temporary file,

    it just makes a FILE * structure with the buffer pointing to the input string.  Not too bad.

     

     



  • Well I know it doesn't physically create any files and probably the reason for using fake FILE data structure was to not double the code for parsing and so on. But the cost for this is ... well, you know that, why should I explain?

     So, once again: please use "n" versions of s[n]scanf and s[n]sprintf, it saves time and memory [literally].

     



  • WTF! Microsoft's c library sourcecode is out in the open?

    Anyway the GNU programmers probably did the opposite: implement that with strings and then use that to write a wrapper to do the same with files. Which makes more sense.



  • @Spacecoyote said:

    WTF! Microsoft's c library sourcecode is out in the open?

    Anyway the GNU programmers probably did the opposite: implement that with strings and then use that to write a wrapper to do the same with files. Which makes more sense.

    Actually, glibc does something far more complicated that allows the definition of new types of stream (and even new % format strings) in client code, by providing your own hook functions that behave vaguely like read(), write(), lseek(), and close(). The code is remarkably straightforward.

    The real WTF here is that people are even considering using some kind of scanf. I have never yet encountered a case where the use of scanf did not constitute a bug. It is not a good function.




Log in to reply