How to use the fgets() function in C
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 bystdinwhen reading from standard input.
- Return Type: On successful read, the pointer to
stris returned. If there was an error or the end of file character is encountered before any content could be read, aNULLpointer 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 stdinputs(str); // print read content out to stdout// open the fileFILE *f = fopen("file.txt" , "r");// if there was an errorif(f == NULL){perror("Error opening file"); // print errorreturn(-1);}// if there was no errorelse{fgets(str, 20, f); // read from fileputs(str); // print read content out to stdout}fclose(f); // close filereturn(0);}
Enter the input below
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved