Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Formatting changes

...

Code Block
bgColor#ccccff
langc
#include <stdio.h>
 
int func(const char *filename) {
  FILE *f = fopen(filename, "r"); 
  if (NULL == f) {
    return -1;
  }

  /* ... */

  if (fclose(f) == EOF) {
    return -1;
  }
  return 0;
}

Noncompliant Code Example (exit())

This code example is noncompliant because the resource allocated by the call to fopen() is not closed before the program terminates.  Although exit() closes the file, if any error occurs when flushing or closing the file, the program has no way of knowing about it.

Code Block
bgColor#FFcccc
langc
#include <stdio.h>
#include <stdlib.h>
  
int main(void) {
  FILE *f = fopen(filename, "w"); 
  if (NULL == f) {
    /* Handle error */
  }

  /* ... */

  exit(EXIT_SUCCESS);
}

Compliant Solution (exit())

In this compliant solution, the program closes f explicitly before it calls exit(), allowing it to handle any error that occurs when flushing or closing the file:

...