Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program does not execute in the correct order

Tags:

c

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 ?

like image 994
hugz Avatar asked May 19 '15 17:05

hugz


1 Answers

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.

like image 66
Eric Renouf Avatar answered Sep 21 '22 03:09

Eric Renouf