Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant code example appends data to a file and then reads from the same file.

Code Block
bgColor#ffcccc
langcpp
char data[BUFFERSIZE];
char append_data[BUFFERSIZE];
char *file_name;
FILE *file;

/* Initialize file_name */

file = fopen(file_name, "a+");
if (file == NULL) {
  /* Handle error */
}

/* initialize append_data */

if (fwrite(append_data, BUFFERSIZE, 1, file) != BUFFERSIZE) {
  /* Handle error */
}
if (fread(data, BUFFERSIZE, 1, file) != 0) {
  /* Handle there not being data */
}

fclose(file);

...

In this compliant solution, fseek() is called in between the output and input, eliminating the undefined behavior.

Code Block
bgColor#ccccff
langcpp
char data[BUFFERSIZE];
char append_data[BUFFERSIZE];
char *file_name;
FILE *file;

/* initialize file_name */

file = fopen(file_name, "a+");
if (file == NULL) {
  /* Handle error */
}

/* Initialize append_data */

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 */
}

fclose(file);

...

This noncompliant code example uses C++ iostreams, but makes the same mistake as the previous noncompliant code example.

Code Block
bgColor#ffcccc
langcpp
{
  char data[BUFFERSIZE];
  char append_data[BUFFERSIZE];
  char *file_name;

  * Initialize file_name and append_data */
  fstream file( file_name, fstream::in | fstream::out | fstream::app);
  file << append_data << ends;
  file >> data;
  // ...
} /* File gets closed here */

...

In this compliant solution, the seekg() member function is called in between the output and input, eliminating the undefined behavior.

Code Block
bgColor#ccccff
langcpp
{
  char data[BUFFERSIZE];
  char append_data[BUFFERSIZE];
  char *file_name;

  * Initialize file_name and append_data */
  fstream file( file_name, fstream::in | fstream::out | fstream::app);
  file << append_data << ends;
	file.seekg(0, ios::beg);
  file >> data;
  // ...
} /* File gets closed here */

...