0
点赞
收藏
分享

微信扫一扫

fflush(stdout)和fflush(stdin)

一葉_code 2022-04-03 阅读 60
c语言

fflush是一个在C语言标准输入输出库中的函数,功能是冲洗流中的信息,该函数通常用于处理磁盘文件。fflush()会强迫将缓冲区内的数据写回参数stream 指定的文件中。

1、fflush(stdout)

fflush(FILE p)是把FILEp指向的流的输出立即写入并清空,所以加上fflush(stdout)就是立即显示到屏幕上。

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

void main()
{
        char str[20];
        pid_t pid=getpid();
        printf("my id is :%d",pid);
        fflush(stdout);     // if delete this line, we can't see the pid we want
        sprintf(str,"kill %d\n",pid);
        system(str);
}

这个程序若没有fflush(stdout)就不会看到pid的输出。

2、fflush(stdin)

第一个程序输入123abc+回车

#include <stdio.h>
#include <stdlib.h>
int main(){
    int a;
    char c;
   
    scanf("%d", &a);
    c = getchar();

    printf("a = %d, c = %c \n", a, c);

    return 0;
}

请添加图片描述

#include <stdio.h>
#include <stdlib.h>
int main(){
    int a;
    char c;
   
    scanf("%d", &a);
    fflush(stdin);
    c = getchar();

    printf("a = %d, c = %c \n", a, c);

    return 0;
}

其实,在这里没有区别,因为我实在Linux平台下编译的。这也是我后来才知道的,大家可以参考一下别人的解释

举报

相关推荐

0 条评论