C printf的输出出现故障

C printf的输出出现故障,c,function,printf,C,Function,Printf,我写了以下内容: #include <stdlib.h> #include <stdio.h> void ExecAsRoot (char* str); int main () { printf ("Host real ip is:"); ExecAsRoot("ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1 -d'/'"); return 0; } void E

我写了以下内容:

#include <stdlib.h>
#include <stdio.h>
void ExecAsRoot (char* str);
int main ()
{
  printf ("Host real ip is:");
  ExecAsRoot("ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'");
  return 0;
 }

void ExecAsRoot (char* str) {
  system (str);
}
而实际输出为:

Host real ip is:7.17.11.29
7.17.11.29
Host real ip is:

这是为什么?

正在缓冲打印F的输出,因为打印的字符串不包含换行符。因此,缓冲区在程序结束前不会被刷新,因此在
系统
命令输出后出现

要刷新缓冲区,请使用
fflush

printf ("Host real ip is:");
fflush(stdout);
ExecAsRoot("ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'");
如果希望对
stdout
的所有写入都取消缓冲,可以使用
setvbuf
禁用缓冲:

setvbuf(stdout, NULL, _IONBF, 0);     // _IONBF = unbuffered
或者更简单地说:

setbuf(stdout, NULL);

然后,所有写入标准输出的内容都会立即出现。

有没有办法隐式地“声明”我需要在每个printf上使用fflush?除了将其包装在包含fflush?@Droidzone的函数中之外,在函数之外不能有可执行语句,例如函数调用。您需要在函数中调用
setbuf
,最好在
main
的开头。使用
setvbuf(stdout,NULL,_IONBF,0)@Droidzone右!已编辑。@Droidzone注意它禁用缓冲,而不是在每个
printf