C Programming

Fgets Function in C

The fgets function is defined in the C standard library (stdio.h) and used to read up to n characters from a specified stream such as standard input stream or file stream) to a string pointed with str.

The C fgets function reads characters until it encounters an End-Of-File (EOF), a newline character, or when n-1 characters are read.

This quick tutorial will discuss how to use the fgets function in C programs.

Basic Usage

The general syntax for the C fgets function is as shown below:

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

The function accepts three parameters, namely:

  1. str – A Pointer to the array of characters where the reads string values are added.
  2. n – An integer value defining the maximum number of characters to be added to the str. The maximum number includes the null terminating character.
  3. stream – A pointer describing a file object to identify the input stream.

Fgets Return Values

On successful execution, the function will return str. If the function encounters an error, it returns a null pointer. Similarly, if the function terminates due to an EOF with no characters read, it returns a null pointer.

NOTE: Although a newline character will force the fgets function to stop, it is still included in the string copied as a valid character.

Fgets Function Example

Let us illustrate how to use the fgets function in C. Consider the example code shown below:

#include <stdio.h>

intmain() {
    FILE *fptr;
char str[100];

//    open file for read
fptr = fopen("fgets.txt", "r");
if (fptr == NULL) {
perror("[-] Error Encountered while opening file!");
else {
if (fgets(str, 100, fptr) !=NULL){

In the example above, the fgets function will open the fgets.txt file, read the first 100-1 (99) characters, and print them on the screen.

If we assume the contents of the fgets.txt file are:

Hello world!, this is fgets function in C.

Compiling and executing the above code should print out the lines above.

HINT: Unlike the gets function, the fgets function is safer since it checks the array bounds, preventing a buffer overflow.


This short guide discussed how to use the fgets function in C language to read characters from a stream until specific conditions are met.

Happy C time!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list