Node:Closing a file, Next:, Previous:Opening a file, Up:High-level file routines



Closing a file

The basic high-level function for closing files is fclose. Simply pass this function a stream, and fopen will close it and break the connection to the corresponding file, first reading any buffered input and writing any buffered output. If the file was closed successfully, fclose will return 0; otherwise, it will return EOF.

It is important to check for errors when you close a stream to which you are writing. For example, when fclose attempts to write the output remaining in its buffer, it might generate an error because the disk is full. Following is an example of closing a file with write access, while checking for errors.

#include <stdio.h>

int main()
{
  FILE *my_stream;
  char my_filename[] = "snazzyjazz.txt";
  int close_error;

  my_stream = fopen (my_filename, "w");
  fprintf (my_stream, "Just a little hello from fprintf.\n");

  close_error = fclose (my_stream);

  if (close_error != 0)
    {
      printf ("File could not be closed.\n");
    }
  else
    {
      printf ("File closed.\n");
    }

  return 0;
}