[gccsdk] Different behaviour between scl and unixlib

John Tytgat John.Tytgat at aaug.net
Mon Sep 27 17:33:53 PDT 2010


In message <425e525c51.Jan-Jaap at iyonix.c2i.net>
          Jan-Jaap van der Geer <jjvdgeer at inbox.com> wrote:

> The end result was that my program did not work as expected. I
> wonder why. This program shows the problem:
> 
> #include <stdio.h>
> 
> int main()
> {
>   char buffer[11];
>   FILE* file = fopen("ram:$.input", "r");
>   int read;
>   char lastchar;
> 
>   buffer[10] = '\n';
>   while ((read = fscanf(file, "%10[^\n]%c", buffer, &lastchar)) != EOF)
>   {
>     printf("read: %i: '%s', lastchar = %i\n", read, buffer, lastchar);
>   }
> 
>   fclose (file);
> 
>   return 0;
> }
> 
> If compiled with -mlibscl it reads all lines in ram:$.input, ten
> chars at a time, until it encounters a LF. Empty lines are not
> really a problem.
> 
> Compiled with unixlib, if it encounters an empty line, it does not
> read anything at all and ends up in a never ending loop.
> 
> Is this correct?

I'm not an fscanf() expert but I believe UnixLib has the correct behaviour
and SCL's one is wrong.  Cfr. http://www.opengroup.org/onlinepubs/009695399/

We have two directives here:

- %10[^\n]
- %c

Normally leading white space characters (and that includes newline) are
skipped before trying to match the conversion specifications but because
of the use of '[' and 'c' the leading white space character skipping is
surpressed.

So:

Input "0123\n" results in fscanf() returns 2 with "0123" and '\n' as buffer
and lastchar result.
Input "0123456789abc\n" results in fscanf() return 2 with "0123456789" and
'a' as buffer and lastchar result and in a next round you get again return
value 2 with "bc" and '\n' as buffer and lastchar result.
Input "  abc\n" gives again return value 2 and "  abc" and '\n' as buffer
and lastchar result.

However, when you have input "\n" you will get 0 as result as it does not
match "%10[^\n]" directive and this means failure.  As the input does not
get consumed, this starts to loop from now on.

John.
-- 
John Tytgat, in his comfy chair at home                                 BASS
John.Tytgat at aaug.net                             ARM powered, RISC OS driven



More information about the gcc mailing list