[LCP]Simple C test

Greg Black gjb at gbch.net
Thu Jul 4 17:52:06 UTC 2002


James Mclean wrote:

| mabey i am missing something?

You already know that you had overlooked the buffering of the
stdout stream.  You would do well to read the relevant manual
pages so that these surprises affect you less often.  While
you're doing that, have a look at the difference if you use
stderr instead of stdout; and see what effect you get from
putting the following line first in your program and leaving out
the repeated calls to fflush():

    setvbuf(stdout, NULL, _IONBF, 0);

And finally, consider the following alternative implementation
of the program and make sure that you understand why it does
what it does:

#include <unistd.h>

int main(void)
{
    int i;
    char buf[3];

    for (i = 1, buf[0] = '\r'; i < 21; i++) {
        buf[1] = i < 10 ? ' ' : i / 10 + '0';
        buf[2] = i % 10 + '0';
        write(1, buf, 3);
        usleep(100000);
    }
    write(1, "\n", 1);
    return 0;
}




More information about the linuxCprogramming mailing list