Fclose

From Wikipedia, the free encyclopedia

The correct title of this article is fclose. The initial letter is shown capitalized due to technical restrictions.

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.

[edit] Example usage

 #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);
   fclose(file_pointer);
   
   return 0;
 }

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