w3resource

C fclose() function

C library function - fclose()

The fclose() function shall cause the stream pointed to by stream to be flushed and the associated file to be closed. Any unwritten buffered data for the stream shall be written to the file; any unread buffered data shall be discarded.

Syntax:

int fclose(FILE *stream)

fclose() Parameters:

Name Description Required /Optional
stream Identifies an address for a file descriptor, which is an area of memory associated with an input or output stream. Required

Return value from fclose()

  • Upon successful completion, fclose() shall return 0; otherwise, it shall return EOF and set errno to indicate the error.

Example: fclose() function

The following program will create a file test.txt, and then it will write some given text and finally it will close the file using fclose() function.

#include <stdio.h>
int main () {
   FILE *fp; 
   fp = fopen("test.txt", "w");
   fprintf(fp, "%s", "The fclose() function shall cause the stream pointed to by stream to be flushed and the associated file to be closed.");
   fclose(fp);   
   return(0);
}

Errors: The fflush() function shall fail if:

  • The file descriptor underlying stream is not valid
  • An attempt was made to write a file that exceeds the maximum file size.
  • An attempt was made to write a file that exceeds the file size limit of the process.
  • The file is a regular file and an attempt was made to write at or beyond the offset maximum associated with the corresponding stream.
  • The fflush() function was interrupted by a signal.
  • There was no free space remaining on the device containing the file or in the buffer used by the fmemopen() function.

 

C Programming Code Editor:

Previous C Programming: C stdio()
Next C Programming: C clearerr()



Follow us on Facebook and Twitter for latest update.