@@ -55,45 +55,46 @@ For additional compatibility information, see [Compatibility](../../c-runtime-li
55
55
## Example
56
56
57
57
``` 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.
59
60
#include < stdio.h>
60
- #include < conio.h>
61
61
62
- int main ( void )
62
+ int * crash_the_program = nullptr ;
63
+
64
+ int main ()
63
65
{
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;
81
90
}
82
91
```
83
92
84
93
``` Input
85
- This is a test
86
- This is a test
94
+ 5
87
95
```
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
97
98
```
98
99
99
100
## See also
0 commit comments