Skip to content

Commit 32ff39b

Browse files
author
Steve Wishnousky
authored
Update fflush sample
Using fflush(stdin) no longer has any effect. This is reflected in the description, not the sample. I've made a new sample that demonstrates using fflush to ensure data is written to a file in case of a crash.
1 parent 230b723 commit 32ff39b

File tree

1 file changed

+32
-31
lines changed

1 file changed

+32
-31
lines changed

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

Lines changed: 32 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -55,45 +55,46 @@ For additional compatibility information, see [Compatibility](../../c-runtime-li
5555
## Example
5656

5757
```C
58-
// crt_fflush.c
58+
// This sample gets a number from the user, then writes it to a file.
59+
// It ensures the write isn't lost on crash by calling fflush.
5960
#include <stdio.h>
60-
#include <conio.h>
6161

62-
int main( void )
62+
int * crash_the_program = nullptr;
63+
64+
int main()
6365
{
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 );
66+
FILE * my_file{};
67+
fopen_s(&my_file, "myfile.txt", "w");
68+
69+
printf("Write a number: ");
70+
71+
int my_number{};
72+
scanf_s("%d", &my_number);
73+
74+
fprintf(my_file, "User selected %d\n", my_number);
75+
76+
// Write data to a file immediately instead of buffering.
77+
fflush(my_file);
78+
79+
if (my_number == 5) {
80+
// Without using fflush, no data was written to the file
81+
// prior to the crash, so the data is lost.
82+
*crash_the_program = 5;
83+
}
84+
85+
// Normally, fflush is not needed as closing the file will write the buffer.
86+
// Note that files are automatically closed and flushed during normal termination.
87+
fclose(my_file);
88+
89+
return 0;
8190
}
8291
```
8392

8493
```Input
85-
This is a test
86-
This is a test
94+
5
8795
```
88-
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
96+
```myfile.txt
97+
User selected 5
9798
```
9899

99100
## See also

0 commit comments

Comments
 (0)