Skip to content

Update fflush sample #1560

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 11, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 36 additions & 30 deletions docs/c-runtime-library/reference/fflush.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: "fflush"
ms.date: "11/04/2016"
ms.date: "09/11/2019"
apiname: ["fflush"]
apilocation: ["msvcrt.dll", "msvcr80.dll", "msvcr90.dll", "msvcr100.dll", "msvcr100_clr0400.dll", "msvcr110.dll", "msvcr110_clr0400.dll", "msvcr120.dll", "msvcr120_clr0400.dll", "ucrtbase.dll", "api-ms-win-crt-stdio-l1-1-0.dll"]
apitype: "DLLExport"
Expand Down Expand Up @@ -56,44 +56,50 @@ For additional compatibility information, see [Compatibility](../../c-runtime-li

```C
// crt_fflush.c
// Compile with: cl /W4 crt_fflush.c
// This sample gets a number from the user, then writes it to a file.
// It ensures the write isn't lost on crash by calling fflush.
#include <stdio.h>
#include <conio.h>

int main( void )
int * crash_the_program = 0;

int main(void)
{
int integer;
char string[81];

// Read each word as a string.
printf( "Enter a sentence of four words with scanf: " );
for( integer = 0; integer < 4; integer++ )
{
scanf_s( "%s", string, sizeof(string) );
printf( "%s\n", string );
}

// You must flush the input buffer before using gets.
// fflush on input stream is an extension to the C standard
fflush( stdin );
printf( "Enter the same sentence with gets: " );
gets_s( string, sizeof(string) );
printf( "%s\n", string );
FILE * my_file;
errno_t err = fopen_s(&my_file, "myfile.txt", "w");
if (my_file && !err)
{
printf("Write a number: ");

int my_number = 0;
scanf_s("%d", &my_number);

fprintf(my_file, "User selected %d\n", my_number);

// Write data to a file immediately instead of buffering.
fflush(my_file);

if (my_number == 5)
{
// Without using fflush, no data was written to the file
// prior to the crash, so the data is lost.
*crash_the_program = 5;
}

// Normally, fflush is not needed as closing the file will write the buffer.
// Note that files are automatically closed and flushed during normal termination.
fclose(my_file);
}
return 0;
}
```

```Input
This is a test
This is a test
5
```

```Output
Enter a sentence of four words with scanf: This is a test
This
is
a
test
Enter the same sentence with gets: This is a test
This is a test
```myfile.txt
User selected 5
```

## See also
Expand Down