Skip to content

Commit ba08827

Browse files
author
Colin Robertson
authored
Merge pull request #1560 from stwish-msft/patch-10
Update fflush sample
2 parents c3a7fb5 + d3b399d commit ba08827

File tree

1 file changed

+36
-30
lines changed

1 file changed

+36
-30
lines changed

docs/c-runtime-library/reference/fflush.md

Lines changed: 36 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
title: "fflush"
3-
ms.date: "11/04/2016"
3+
ms.date: "09/11/2019"
44
apiname: ["fflush"]
55
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"]
66
apitype: "DLLExport"
@@ -56,44 +56,50 @@ For additional compatibility information, see [Compatibility](../../c-runtime-li
5656

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

62-
int main( void )
64+
int * crash_the_program = 0;
65+
66+
int main(void)
6367
{
64-
int integer;
65-
char string[81];
66-
67-
// Read each word as a string.
68-
printf( "Enter a sentence of four words with scanf: " );
69-
for( integer = 0; integer < 4; integer++ )
70-
{
71-
scanf_s( "%s", string, sizeof(string) );
72-
printf( "%s\n", string );
73-
}
74-
75-
// You must flush the input buffer before using gets.
76-
// fflush on input stream is an extension to the C standard
77-
fflush( stdin );
78-
printf( "Enter the same sentence with gets: " );
79-
gets_s( string, sizeof(string) );
80-
printf( "%s\n", string );
68+
FILE * my_file;
69+
errno_t err = fopen_s(&my_file, "myfile.txt", "w");
70+
if (my_file && !err)
71+
{
72+
printf("Write a number: ");
73+
74+
int my_number = 0;
75+
scanf_s("%d", &my_number);
76+
77+
fprintf(my_file, "User selected %d\n", my_number);
78+
79+
// Write data to a file immediately instead of buffering.
80+
fflush(my_file);
81+
82+
if (my_number == 5)
83+
{
84+
// Without using fflush, no data was written to the file
85+
// prior to the crash, so the data is lost.
86+
*crash_the_program = 5;
87+
}
88+
89+
// Normally, fflush is not needed as closing the file will write the buffer.
90+
// Note that files are automatically closed and flushed during normal termination.
91+
fclose(my_file);
92+
}
93+
return 0;
8194
}
8295
```
8396
8497
```Input
85-
This is a test
86-
This is a test
98+
5
8799
```
88100

89-
```Output
90-
Enter a sentence of four words with scanf: This is a test
91-
This
92-
is
93-
a
94-
test
95-
Enter the same sentence with gets: This is a test
96-
This is a test
101+
```myfile.txt
102+
User selected 5
97103
```
98104

99105
## See also

0 commit comments

Comments
 (0)