C fgets Function

The C fgets function is 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 an example?. Use the fgetc function to read character by character from the stream.

C fgets Syntax

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

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

From the above C fgets 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 will use the following specified file to demonstrate this C fgets function.

Sample Text File 1

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

C fgets example

The C fgets method reads 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 fgets function.

#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);
   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 txt in the reading mode because we wanted to read the characters present in the sample.txt. Please refer to the fgetc function and the read inputs article.

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

The following If Statement will check whether we successfully opened the sample.txt 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 the end or not.

while (!feof(fileAddress)) {

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

fgets(data, 50, fileAddress);

Next, we close the C programming pointer.