C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs



Home » C programs » stdio.h header file functions

fgets() function of stdio.h in C






In this article, we are going to learn about the fgets() function of stdio.h header file in C programming language and use it while getting the characters from file pointer.
Submitted by Abhishek Sharma, on April 13, 2018

If you are handling files in your application then reading from a file is something that you cannot ignore. Therefore, the function fgets() will help you doing this.

The Function is use to read a string from a file. The Function needs only three parameters, first a character array, second is the number of character you want to read and the third is the file itself.

Example:

    fgets (str, 60, F); 
    //Here, str is a character array, F is the file variable.

It will read 60 characters from the file from the current position of the cursor.

stdio.h - fgets() function Example in C

#include <stdio.h>

int main ()
{
	//initializing the file pointer 
	//and type of variables
	FILE *F;
	char str[60];

	//open file abc in read mode
	F = fopen("abc.txt" , "r");

	if(F == NULL) {
		perror("Error is:");
		return(-1);
	}
	if( fgets (str, 60, F)!=NULL ) {
		//printing the output on console
		puts(str);
	}
	fclose(F);

	return(0);
}

Output

stdio.h - fgets() in c language






You may also be interested in...

C/C++ Tips and Tricks...

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.


Comments and Discussions