C fgets Function

The C fgets function used to read an array of characters from the specified stream. How to read the character array or string data from File and return output using fgets in C Programming with example?. Use the fgetc function to read character by character.

Syntax of fgets in C Programming

The syntax behind the fgets in C Programming language is as shown below.

char *fgets(char *str, int n, FILE *stream)

From the above fgets function code snippet,

  • str: Please specify the array of characters you want to read from the file
  • n: The maximum length that the fgets function can read.
  • stream: Please specify the pointer to a FILE object, or simply say, file pointer that holds the file address and the operation mode

We are going to use the following specified file to demonstrate this fgets function.

C FGETS Function 1

From the above screenshot, you can observe that the sample.txt file is in our C File Examples folder. And it contains text as Learn C Programming Language at Tutorial Gateway.

C fgets example

The fgets method is used to read the array of characters from the user-specified file and returns the output. This C program will help you to understand the same.

TIP: You have to include the #include<stdio.h> header before using this C fgets function.

// C fgets function example
#include <stdio.h> 
int main()
{
   FILE *fileAddress;
   fileAddress = fopen("sample.txt", "r");
   char data[50];
	
   if (fileAddress != NULL) {
	// Check whether it is the last character or not
	while (!feof(fileAddress)) {
		
		// fgets(string_data, number_of_characters(length), file_pointer)
		fgets(data, 50, fileAddress);
		printf("Character we are reading from the File = %s \n", data);
	}
	fclose(fileAddress);		
   }
   else {
	printf("\n Unable to Create or Open the Sample.txt File");
   }
   return 0;
}
C FGETS Function 2

Within this C fgets function example, First, we created the File pointer and then assigned the file in read mode because we want to read the characters present in the sample.txt. Please refer to fgetc function article.

TIP: In this C program, we haven’t mentioned the full path of file name because my .c application and the text file reside in the same location. If your scenario is different then, please provide the full path.

FILE *fileAddress;
fileAddress = fopen("sample.txt", "r");

The following If Statement will check whether we successfully opened the sample.txt file or not.

if (fileAddress != NULL) {

Next, we used the While Loop to traverse each character present in the sample.txt. Within the while loop, we used the condition to check whether the compiler reached to the file end or not.

while (!feof(fileAddress)) {

Next, we used the C fgets function to read the string or array of characters present in the sample.txt file. Her 50 is a maximum length

fgets(data, 50, fileAddress);

Next, we are closing the C programming file pointer.

fclose(fileAddress);