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.

C Programming: Tips of the Day

Reading a string with scanf :

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

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