Previous Page
Next Page

fclose

Closes a file or stream

#include <stdio.h>
int fclose ( 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;
}

See Also

fflush( ), fopen( ), setbuf( )


Previous Page
Next Page