fclose()

Close an open file.

  #include <stdio.h>
  
  int fclose(FILE *stream);    
Parameter

stream

A pointer to a FILE stream

Remarks

The fclose() function closes a file created by fopen(), freopen(), or tmpfile(). The function flushes any buffered data to its file and closes the stream. After calling fclose(), stream is no longer valid and cannot be used with file functions unless it is reassigned using fopen(), freopen(), or tmpfile().

All of a program's open streams are flushed and closed when a program terminates normally.

fclose() closes then deletes a file created by tmpfile().

On embedded and real-time operating systems this function may only be applied to the stdin, stdout, and stderr files.

fclose() returns a zero if it is successful and returns an EOF if it fails to close a file.

Listing: Example of fclose() usage

#include <stdio.h>

#include <stdlib.h>

int main(void)

{

FILE *f;

static char name[] = "myfoo";

// create a new file for output

if ( (f = fopen(name, "w")) == NULL) {

printf("Can't open %s.\n", name);

exit(1);

}

// output text to the file

fprintf(f, "pizza sushi falafel\n");

fprintf(f, "escargot sprocket\n");

// close the file

if (fclose(f) == -1) {

printf("Can't close %s.\n", name);

exit(1);

}

return 0;

}

Output to file myfoo:

pizza sushi falafel

escargot sprocket