5

There are in my code functions that take a while to execute, like calculating the number of words in big files. I want to show to the user an output like this :

calculating word number ...

Execute the function then print : calculating word number ... OK

To do that, i have in my main :

int main(int argc, char * argv[])
{
    int number_of_words;
    FILE * dico = NULL;
    dico = fopen(argv[1],"r+");

    printf("calculating word number ...");
    number_of_words = number(dico);
    printf("OK\n");

    return 3.14;
}

And the function that calculates the number of words is :

int number(FILE * dico)
{
    int n=0;
    char mot[20];

    rewind(dico);

    while (fgets(mot, 20, dico) != NULL)
    {
        n+=1;
    }

    return n;
}

After executing the function for a really big file for input, it appears that the output is not as attended. In fact, the waiting time is before the first printf("calculating word number ..."); and then when it is over all the printf are done together.

Why does this happen ?

hugz
  • 63
  • 1
  • 6
  • 2
    possible duplicate of [Why does printf not flush after the call unless a newline is in the format string?](http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin) – dbarnes May 19 '15 at 17:33
  • 1
    Welcome to the difference between buffered and unbuffered I/O. – Scott Hunter May 19 '15 at 17:34

1 Answers1

6

Your output is being buffered. Since there is no line ending on your first print, it is being buffered by stdout and not displayed. If there was enough characters it would write it, or if it had a line ending, or stdout was flushed or it was written to an unbuffered stream (like stderr) it would probably show up right away.

It's still being executed in the right order though, it just isn't displaying things immediately.

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
  • I used fflush(stdout) before executing the function and now it works great ! Thanks a lot !! – hugz May 19 '15 at 17:46