...
Receiving input from a stream directly following an output to that stream without an intervening call to fflush()
, fseek()
, fsetpos()
, or rewind()
, or outputting to a stream after receiving input from it without a call to fseek()
, fsetpos()
, rewind()
if the file is not at end-of-file results in undefined behavior. Consequently, a call to one of these functions is necessary in between input and output to the same stream in most cases.
Non-Compliant Code Example
...
Code Block | ||
---|---|---|
| ||
char data[BUF_SIZ];
char append_data[BUF_SIZ];
FILE *file;
file = fopen(file_name, "a+");
if (file == NULL) {
/* handle error */
}
/* Initialize append_data */
if (fwrite(append_data, BUF_SIZ, 1, data) != BUF_SIZ) {
/* Handle error */
}
if (fread(data, BUF_SIZ, 1, file) != 0) {
/* Handle there not being data */
}
fclose(file);
|
...
Code Block | ||
---|---|---|
| ||
char data[BUF_SIZ];
char append_data[BUF_SIZ];
FILE *file;
file = fopen(file_name, "a+");
if (file == NULL) {
/* handle error */
}
/* Initialize append_data */
if (fwrite(append_data, BUF_SIZ, 1, data) != BUF_SIZ) {
/* Handle error */
}
fflush(file);
if (fread(data, BUF_SIZ, 1, file) != 0) {
/* Handle there not being data */
}
fclose(file);
|
Risk Assessment
Alternately inputing and outputing outputting from a stream without an intervening flush or positioning call results in undefined behavior.
...