6.18.11 fclose Function

Close a stream.

Attention: This function is not implemented by MPLAB XC8 for PIC MCUs. It is implemented by all other compilers, but MPLAB XC8 for AVR MCUs has limited support of data streams.

Include

<stdio.h>

Prototype

int fclose(FILE * stream);

Argument

stream
pointer to the stream to close

Return Value

Returns 0 if successful; otherwise, returns EOF if any errors were detected.

Remarks

The fclose function causes the stream indicated by the argument to be flushed and the associated file to be closed. This function requires a heap.

Example

See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

#include <stdio.h>

int main(void)
{
  FILE *myfile1, *myfile2;
  int y;

  if ((myfile1 = fopen("afile1", "w+")) == NULL)
    printf("Cannot open afile1\n");
  else
  {
    printf("afile1 was opened\n");

    y = fclose(myfile1);
    if (y == EOF)
      printf("afile1 was not closed\n");
    else
      printf("afile1 was closed\n");
  }
}

Example Output

afile1 was opened
afile1 was closed