Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: close/fclose error checks

...

Code Block
bgColor#ffcccc
langc
#include <stdio.h>
 
void func(const char *file_name) {
  FILE *fptr;

  int c = getc(fptr = fopen(file_name, "r"));
  if (feof(stdin) || ferror(stdin)) {
    /* Handle error */
  }

  if (fclose(fptr); == EOF) {
    /* Handle error */
  }
}

This noncompliant code example also violates  ERR33-C. Detect and handle standard library errors because the value returned by fopen() is not checked for errors.

...

Code Block
bgColor#ccccff
langc
#include <stdio.h>
 
void func(const char *file_name) {
  int c;
  FILE *fptr;

  fptr = fopen(file_name, "r");
  if (fptr == NULL) {
    /* Handle error */
  }

  c = getc(fptr);
  if (feof(stdin) || ferror(stdin)) {
    /* Handle error */
  }

  if (fclose(fptr); == EOF) {
    /* Handle error */
  }
}

Noncompliant Code Example (putc())

...

Code Block
bgColor#ffcccc
langc
#include <stdio.h>
 
void func(const char *file_name) {
  FILE *fptr = NULL;
  int c = 'a';
 
  while (c <= 'z') {
    if (putc(c++, fptr ? fptr :
         (fptr = fopen(file_name, "w")) == EOF) {
      /* Handle error */
    }
  }

  if (fclose(fptr); == EOF) {
    /* Handle error */
  }
}

If the putc() macro evaluates its stream argument multiple times, this might still seem safe, as the ternary conditional expression ostensibly prevents multiple calls to fopen(). However, there is no guarantee that these calls would happen in distinct sequence points. Consequently, this code also violates EXP30-C. Do not depend on order of evaluation for side effects.  This code also violates ERR33-C. Detect and handle standard library errors because it fails to check the return value from fopen().

...

Code Block
bgColor#ccccff
langc
#include <stdio.h>
 
void func(const char *file_name) {
  int c = 'a'; 
  FILE *fptr = fopen(file_name, "w");
 
  if (fptr == NULL) {
    /* Handle error */
  }

  while (c <= 'z') {
    if (putc(c++, fptr) == EOF) {
      /* Handle error */
    }
  }

  if (fclose(fptr); == EOF) {
    /* Handle error */
  }
}

The expression c++ is perfectly safe because putc() guarantees to evaluate its character argument exactly once.

...