cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : C Library : cstdio (stdio.h) : fflush
 
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forum
Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
C Library
cassert (assert.h)
cctype (ctype.h)
cerrno (errno.h)
cfloat (float.h)
climits (limits.h)
clocale (locale.h)
cmath (math.h)
csetjmp (setjmp.h)
csignal (signal.h)
cstdarg (stdarg.h)
cstddef (stddef.h)
cstdio (stdio.h)
cstdlib (stdlib.h)
cstring (string.h)
ctime (time.h)
cstdio (stdio.h)
functions:
· clearerr
· fclose
· feof
· ferror
· fflush
· fgetc
· fgetpos
· fgets
· fopen
· fprintf
· fputc
· fputs
· fread
· freopen
· fscanf
· fseek
· fsetpos
· ftell
· fwrite
· getc
· getchar
· gets
· perror
· printf
· putc
· putchar
· puts
· remove
· rename
· rewind
· scanf
· setbuf
· setvbuf
· sprintf
· sscanf
· tmpfile
· tmpnam
· ungetc
· vfprintf
· vprintf
· vsprintf
macro constants:
· EOF
· FILENAME_MAX
· NULL
· TMP_MAX
objects:
· stderr
· stdin
· stdout
types:
· FILE
· fpos_t
· size_t

-

fflush function
int fflush ( FILE * stream );
<cstdio>

Flush stream

If the given stream was open for writing and the last i/o operation was an output operation, any unwritten data in the output buffer is written to the file.
If the stream was open for reading, the behavior depends on the specific implementation. In some implementations this causes the input buffer to be cleared.
If the argument is a null pointer, all open files are flushed.
The stream remains open after this call.
When a file is closed, either because of a call to fclose or because the program terminates, all the buffers associated with it are automatically flushed.

Parameters

stream
Pointer to a FILE object that specifies a buffered stream.

Return Value

A zero value indicates success.
If an error occurs, EOF is returned and the error indicator is set (see feof).

Example

To illustrate the use of fflush, we ask twice the user to write some words in a sentence. Each time the program reads the first word with scanf and flushes the stream, discarding the rest. The next time the user is prompt, the buffer is empty so we are able to obtain again only the first word of the new sentence:

/* fflush example */
#include <stdio.h>
int main()
{
   int n;
   char string[80];
   for ( n=0 ; n<2 ; n++ )
   {
     printf( "Enter some words: " );
     scanf( "%s", string );
     printf( "The first word you entered is : %s\n", string );
     fflush ( stdin );
   }
   return 0;
}

Output:

Enter some words: Testing this program
The first word you entered is : Testing
Enter some words: It seems to work properly...
The first word you entered is : It

See also

fclose Close file (function)
fopen Open file (function)
setbuf Set stream buffer (function)
setvbuf Change stream buffering (function)
© The C++ Resources Network, 2000-2007 - All rights reserved
Spotted an error? - contact us