CERT-FIO39-C
Synopsis
Do not alternately input and output from a stream without an intervening flush or positioning call.
Enabled by default
Yes
Severity/Certainty
Low/High

Full description
Receiving input from a stream directly following an output to that stream, or outputting to a stream after receiving input from that stream, without an intervening call to fflush(), fseek(), fsetpos(), or rewind() if the file is not at end-of-file is undefined behaviour. Consequently, a call to fseek(), fflush(), or fsetpos() is necessary between input and output to the same stream.
Coding standards
- CERT FIO39-C
Do not alternately input and output from a stream without an intervening flush or positioning call
- CWE 664
Improper Control of a Resource Through its Lifetime
Code examples
The following code example fails the check and will give a warning:
#include <stdio.h>
enum { BUFFERSIZE = 32 };
extern void initialize_data(char *data, size_t size);
void func(const char *file_name) {
char data[BUFFERSIZE];
char append_data[BUFFERSIZE];
FILE *file;
file = fopen(file_name, "a+");
if (file == NULL) {
/* Handle error */
}
initialize_data(append_data, BUFFERSIZE);
if (fwrite(append_data, 1, BUFFERSIZE, file) != BUFFERSIZE) {
/* Handle error */
}
if (fread(data, 1, BUFFERSIZE, file) < BUFFERSIZE) {
/* Handle there not being data */
}
if (fclose(file) == EOF) {
/* Handle error */
}
}
The following code example passes the check and will not give a warning about this issue:
#include <stdio.h>
enum { BUFFERSIZE = 32 };
extern void initialize_data(char *data, size_t size);
void func(const char *file_name) {
char data[BUFFERSIZE];
char append_data[BUFFERSIZE];
FILE *file;
file = fopen(file_name, "a+");
if (file == NULL) {
/* Handle error */
}
initialize_data(append_data, BUFFERSIZE);
if (fwrite(append_data, BUFFERSIZE, 1, file) != BUFFERSIZE) {
/* Handle error */
}
if (fseek(file, 0L, SEEK_SET) != 0) {
/* Handle error */
}
if (fread(data, BUFFERSIZE, 1, file) != 0) {
/* Handle there not being data */
}
if (fclose(file) == EOF) {
/* Handle error */
}
}