Trusted answers to developer questions

How to use the fgets() function in C

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

The fgets() function in C reads up to n characters from the stream (file stream or standard input stream) to a string str. The fgets() function keeps on reading characters until:

  • (n-1) characters have been read from the stream.
  • a newline character is encountered.
  • end of file (EOF) is reached.

fgets terminates at the newline character but appends it at the end of the string str. The function also appends the terminating null character at the end of the passed string.


Syntax

char* fgets(char* str, int n, FILE* stream);
  • Arguments
    • char* str: pointer to an initialized string in which characters are copied.
    • int n: number of characters to copy.
    • FILE* stream: pointer to the file stream, this can be replaced by stdin when reading from standard input.
  • Return Type: On successful read, the pointer to str is returned. If there was an error or the end of file character is encountered before any content could be read, a NULL pointer is returned.

Examples

fgets is safe to use in comparison to gets since it checks for character array str bounds. gets keeps on reading characters from the users, until a newline character is encountered.

main.c
file.txt
#include <stdio.h>
int main(){
char str[20];
fgets(str, 20, stdin); // read from stdin
puts(str); // print read content out to stdout
// open the file
FILE *f = fopen("file.txt" , "r");
// if there was an error
if(f == NULL){
perror("Error opening file"); // print error
return(-1);
}
// if there was no error
else{
fgets(str, 20, f); // read from file
puts(str); // print read content out to stdout
}
fclose(f); // close file
return(0);
}

Enter the input below

RELATED TAGS

c
stdin
input
string
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?