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()



Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, i.e.: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

Ref : https://bit.ly/3CbzF8M