UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

9.2.3.  Closing a file

After a disk file is read, written, or appended with some new data, you have to disassociate the file from the specified stream. This is done by calling the fclose function:

#include <stdio.h>
int fclose(FILE *stream);

If fclose closes a file successfully, it returns 0. Otherwise, the function returns EOF. Normally, this function fails only when the disk is removed before the function is called or there is no more space left on the disk. Remember to close a file after the I/O operations. Otherwise, the data saved in the file may be lost. In addition, failing to close a file when you are done with it may prevent other programs from accessing the file later.

The next program shows how to open and close a text file, checking the values returned from the functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>

enum {SUCCESS, FAIL};
int main(void)
{
  FILE *file_ptr;
  char filename[] = "review.txt";
  int result = SUCCESS;

  if ( (file_ptr = fopen(filename, "r") ) == NULL) 
  {
    printf("Cannot open %s.\n", filename);
    result = FAIL;
  }
  else 
  {
    printf("File opened; ready to close it.\n");
    if (fclose(file_ptr) != 0) 
    {
      printf("Cannot close %s.\n", filename);
      result = FAIL;
    }
  }
  return result;
}