| Failing to close files when they are no longer needed may allow attackers to exhaust and possibly manipulate system resources. This phenomenon is typically referred to as file descriptor leakage \[[CWE 403|http://cwe.mitre.org/data/definitions/403.html]\], although file pointers may also be used as an attack vector. To prevent file descriptor leaks, file pointers and file descriptors should be closed when they are no longer needed. | 
fopen()In this non-compliant example, an array of characters is written to the end of a file. However, if fwrite() fails, then write_data() returns -1 in error without properly closing the stream to DataFile.txt.
| 
int write_data(char *data, size_t data_size) {
  FILE * fptr;
  size_t written;
  fptr = fopen("DataFile.txt", "a");
  if (fptr == NULL) {
    /* Handle fopen() error */
  }
  written = fwrite(data, sizeof(char), data_size, fptr);
  if (written < data_size) {
    return -1;
  }
  fclose(fptr);
  return 0;
}
 | 
To correct this example, the code is modified to ensure DataFile.txt is always closed.
| 
int write_data(char *data, size_t data_size) {
  FILE * fptr;
  size_t written;
  int result = 0;
  fptr = fopen("DataFile.txt", "a");
  if (fptr == NULL) {
    /* Handle fopen() error */
  }
  written = fwrite(data, sizeof(char), data_size, fptr);
  if (written < data_size) {
    result = -1;
  }
  fclose(fptr);
  return result;
}
 | 
open()Failing to properly close files may allow unintended access to system resources, or exhaust system resources.