在我的代码中有一些函数需要一段时间才能执行,比如计算大文件中的字数。我想展现给用户这样的输出:C程序没有以正确的顺序执行
calculating word number ...
执行功能,然后打印:calculating word number ... OK
要做到这一点,我在我的主:
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;
}
而且计算字数的函数为:
int number(FILE * dico)
{
int n=0;
char mot[20];
rewind(dico);
while (fgets(mot, 20, dico) != NULL)
{
n+=1;
}
return n;
}
执行真正大文件输入的函数后,看起来输出不如参与。其实等待的时间是之前第一个printf("calculating word number ...");
然后当它是所有的printf
一起完成。
为什么会发生这种情况?
可能的重复[为什么printf在调用后不刷新,除非换行符在格式字符串中?](http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-除非换行符在格式中) – dbarnes
欢迎使用缓冲和非缓冲I/O之间的区别。 –