[关闭]
@snuffles 2015-03-09T16:40:59.000000Z 字数 1527 阅读 1758

fflush(NULL)

c


reference
man

FFLUSH(3) Linux Programmer's Manual FFLUSH(3)

NAME
fflush - flush a stream

SYNOPSIS

   #include <stdio.h>

   int fflush(FILE *stream);

DESCRIPTION
For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underly‐ing write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application. The open status of the stream is unaffected.

If the stream argument is NULL, fflush() flushes all open output streams.For a nonlocking counterpart, see unlocked_stdio(3).

RETURN VALUE
Upon successful completion 0 is returned. Otherwise, EOF is returned and errno is set to indicate the error.

ERRORS
EBADF Stream is not an open stream, or is not open for writing.
The function fflush() may also fail and set errno for any of the errors specified for write(2).

NOTES
Note that fflush() only flushes the user-space buffers provided by the C library. To ensure that the data is physically stored on disk the
kernel buffers must be flushed too, for example, with sync(2) or fsync(2).


fflush用于清空缓冲流,虽然一般感觉不到,但是默认printf是缓冲输出的。 fflush(stdout),使stdout清空,就会立刻输出所有在缓冲区的内容。 fflush(stdout)这个例子可能不太明显,但对stdin很明显。 如下语句:

  1. int a,c;
  2. scanf("%d",&a);
  3. c=getchar();

输入: 12(回车) 那么 a=12 ,c= '\n'

  1. int a,c;
  2. scanf("%d",&a);
  3. fflush(stdin);
  4. c=getchar();

输入: 12(回车) 那么a=12,
c暂时未得到输入值,还需要再输入c,因为getchar也是缓冲输入,'\n'本还在缓冲区,但是被清空了。

另外fflush不能作用于重定向输入流。fflush(stdin)刷新标准输入缓冲区,把输入缓冲区里的东西丢弃fflush(stdout)刷新标准输出缓冲区,把输出缓冲区里的东西打印到标准输出设备上

fflush(stdout);——fflush()的作用是:如果圆括号里是已写打开的文件的指针,则将输出缓冲区的内容写入该指针指向的文件,否则清除输出缓冲区。这里的stdout是系统定义的标准输出文件指针,默认情况下指屏幕,那就是把缓冲区的内容写到屏幕上。可是从代码中看不出缓冲区会有什么内容,所以它实际上没有起什么作用

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注