Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is fgets() in C?

Kainat Asif

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

fgets() is a standard C library function that is used to read a string of characters from a file at the location indicated by the file pointer. Below is the declaration of the fgets() function:

char *fgets (char * str,int size, FILE * stream);

Return value

if the read operation from the file is successful, the fgets() function return the string that is read. EOFEnd-of-File is returned if there is an error when reading from the file.

Parameters of the fgets() function

  • str: Pointer to the character array to store the string read from the file.
  • size: Maximum number of characters that can be read from the file.
  • stream: Pointer to the file from which the character is to be read.

Example

Consider the code snippet below, which uses fgets() to read the content of a file:

main.c
fgetsExample.txt
#include <stdio.h>
int main() {
FILE * fPointer;
char str[100];
fPointer = fopen ("fgetsExample.txt", "r");//opening file
while( !feof(fPointer) )//checking EOF
{
fgets(str, 100, fPointer);
if(str!=NULL)//if EOF returned
{
printf("%s",str);
}
}
fclose(fPointer);
return 0;
}

The fgets() function is used in line 12, which reads and subsequently prints the content of the file fgetsExample.txt on the screen.

RELATED TAGS

c

CONTRIBUTOR

Kainat Asif
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring