Home » C programs » stdio.h header file functions

fclose() function in C language with Example

Here, we are going to learn about the fclose() function of library header stdio.h in C language with its syntax, example/program.
Submitted by Souvik Saha, on January 06, 2019

fclose() function in C

Prototype:

    int fclose(FILE *filename);

Parameters:

    FILE *filename

Return type: int

Use of function:

When we are dealing with several files in our program and after operations are over if we do not close the files then some unwanted modifications (like a modification of data, destroy files, lost of data etc) occurs. So after our file handling operations are over we have to close the opened file and fclose() function is used for closing the opened files. The prototype of this function is int fclose(FILE *filename);

If the fclose() function returns the value zero then it is successfully executed, otherwise, it returns the value EOF which refers an error occurs. fclose() function fails when the file permanently removes from the disk.

fclose() example in C

#include <stdio.h>
#include <stdlib.h>

int main(){
	FILE *f;
	char str[100];

	//Check the existence of that file
	if((f=fopen("includehelp.txt","r"))==NULL){
		printf("Cannot open the file...");
		//if not exist program is terminated
		exit(1);
	}

	printf("File content is--\n");
	//print the strings until EOF is encountered
	while(!feof(f)){
		fgets(str,100,f);
		//print the string
		printf("%s",str);
	}

	//close the opened file
	fclose(f);
	
	return 0;
}

Output

fclose example in c





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.