Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Closing a file

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;
}

 
 
  Published under free license. Design by Interspire