Name

fclose

Synopsis

Closes a file or stream

#include <stdio.h>
intfclose( FILE *fp );

The fclose() function closes the file associated with a given FILE pointer, and releases the memory occupied by its I/O buffer. If the file was opened for writing, fclose() flushes the contents of the file buffer to the file.

The fclose() function returns 0 on success. If fclose() fails, it returns the value EOF.

Example

/* Print a file to the console, line by line. */
FILE *fp_infile;
char linebuffer[512];

if (( fp_infile=fopen("input.dat", "r")) == NULL )
{
  fprintf(stderr, "Couldn't open input file.\n");
  return -1;
}

while ( fgets( linebuffer, sizeof(linebuffer), fp_infile )) != NULL )
  fputs( linebuffer, stdout );
if ( ! feof(fp_infile) )   // This means "if not end of file"
  fprintf( stderr, "Error reading from input file.\n" );

if ( fclose(fp_infile) != 0 )
{
  fprintf(stderr, "Error closing input file.\n");
  return -2;
}

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.