You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WSL2中printf在system命令后执行的顺序问题及解决咨询

解决C语言printf与system输出顺序颠倒的问题

这是标准输出的行缓冲机制导致的:默认情况下,标准输出连接终端时采用行缓冲模式,printf("Current date is : ")没有换行符,输出内容会暂存到缓冲区,不会立刻打印到终端;而system("date")调用的shell命令会直接将输出刷新到终端,因此出现顺序颠倒的现象。

以下是几种可行的解决方法:

  • 手动刷新缓冲区(推荐):在printf后调用fflush(stdout)强制输出缓冲区内容,同时记得包含stdlib.h头文件(system函数依赖它):
#include<stdio.h>
#include<stdlib.h>

int main(){
    printf("Current date is : ");
    fflush(stdout); // 强制刷新标准输出缓冲区
    system("date");
    printf("\n");
    return 0;
}
  • 给printf添加换行符:在输出字符串末尾加上\n,触发行缓冲自动刷新(但会改变输出格式,让Current date is : 单独占一行):
#include<stdio.h>
#include<stdlib.h>

int main(){
    printf("Current date is : \n");
    system("date");
    printf("\n");
    return 0;
}
  • 关闭标准输出缓冲:在程序开头用setbuf(stdout, NULL)禁用缓冲,所有printf内容会立刻输出(不推荐频繁使用,会影响输出效率):
#include<stdio.h>
#include<stdlib.h>

int main(){
    setbuf(stdout, NULL); // 关闭标准输出缓冲
    printf("Current date is : ");
    system("date");
    printf("\n");
    return 0;
}

内容的提问来源于stack exchange,提问作者Joe Race

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 17:46:27