c语言中清除缓冲区的函数,关于C语言的清除缓冲区

1:本短文介绍三种方式清除C语言编译时printf的缓存:

第一种:setbuf(stdin,NULL);

头文件:include

第二种:_

_fpurge(stdin);(相当于Unix下面的fflush()。)

头文件:include

第三种:while((c=getchar())!='\n'&&!=EOF);

其中以第二种方式最为有效与普遍。

2:下面贴上百度对setbuf与网上其他对_ _fpurge的详细解析:

setbuf:

函数名:

setbuf

功 能:

把缓冲区与流相联

用 法:

void setbuf(FILE *steam, char *buf);

说明:setbuf函数具有打开和关闭缓冲机制。为了带缓冲进行I/O,参数buf必须指向一个长度为BUFSIZ(定义

在stdio.h头文件中)的缓冲区。通常在此之后该流就是全缓冲的,但是如果该流与一个终端设备相关,那么某些系统也可以将其设置为行缓冲。为了关闭缓冲,可以将buf参数设置为NULL。

程序例:

#include

char

outbuf[50];

int

main(void)

{

setbuf(stdout,outbuf);

puts("This is a test of buffered output.");

puts("This output will go into outbuf");

puts("and won't appear until the buffer");

puts("fills up or we flush the stream.\n");

puts(outbuf);

fflush(stdout);

return

0;

}

fpurge:(英文版)

_

_fpurge

fpurge,

__fpurge - purge a stream

synopsis

#include

#include

void __fpurge(FILE *stream);

description

The function fpurge() clears

the buffers of the given stream. For output

streams this discards any unwritten output. For

input streams this discards

any input read from the underlying object but not yet obtained via

getc(3);

this includes any text pushed back via ungetc(3). See

also fflush(3).

The function __fpurge() does

precisely the same, but without returning a

value.

return value

Upon successful completion fpurge() returns 0. On

error, it returns -1 and

sets errno appropriately.

errors

EBADF stream is not an open

stream.

conforming

These functions are nonstandard and not portable. The function fpurge() was

introduced in 4.4BSD and is not available under Linux. The function

__fpurge() was introduced in Solaris, and is present in glibc 2.1.95 and

later.

notes

Usually it is a mistake to want to discard input buffers.

3:fflush用于将缓冲区中尚未写入文件的数据强制性地保存到文件中

#include

int fflush(FILE *fp);

fpurge用于将缓冲区内的数据完全清除

你可能感兴趣的:(c语言中清除缓冲区的函数)