fgets() in C

File reading can be tricky for an amateur programmer; however, C++ has made it easier with the fgets() function that allows files to be read.

Syntax

fgets() takes three parameters that are defined when the function is called. The following code explains how the function is declared:

char *fgets(char *string, int size, FILE *filePointer)

Parameters

  • string: the target character array where the file data is read and stored.
  • size: the amount of characters we want to read in the file.
  • filePointer: points to the file being read.

Code

The following code reads a file named "file.txt" up to 10 characters and stores it in string s. file.txt has a string of i love educative and programming, but string s only reads the first 10 characters.

main.c
file.txt
#include <stdio.h>
int main()
{
int size = 10;
char s [size];
FILE * filePointer;
filePointer = fopen("file.txt" , "r");
fgets(s, size, filePointer);
printf("string is: %s\n", s);
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved