C Programming/stdio.h/fclose

From Wikibooks, open books for an open world
Jump to navigation Jump to search

fclose is a C function belonging to the ANSI C standard library, and included in the file stdio.h. Its purpose is close a stream and all the structure associated with it. Usually the stream is an open file. fclose has the following prototype:

int fclose(FILE *file_pointer)

It takes one argument: a pointer to the FILE structure of the stream to close, eg: :fclose(my_file_pointer) This line call the function fclose to close FILE stream structure pointed by my_file_pointer.

The return value is an integer with the following meaning:

  • 0 (zero): the stream was closed successfully;
  • EOF: an error occurred;

One can check for an error by reading errno. fclose has undefined behavior if it attempts to close a file pointer that isn't currently assigned to a file - in many cases, this results in a program crash.

It is usually a wrapper for a close (system call).

Example usage[edit | edit source]

 #include <stdio.h>

 int main(void) 
   FILE *file_pointer;
   int i;
   file_pointer = fopen("myfile.txt", "r");
   fscanf(file_pointer, "%d", &i);
   printf("The integer is %d\n", i);
   return 0;

The above program opens a file called myfile.txt and scans for an integer in it.