fgets() in C

Last Updated : 23 Jul, 2026

fgets() is a standard library function in C that reads a line of text from a specified input stream and stores it in a character array. It is defined in the <stdio.h> header file and provides a safe way to read strings.

  • Reads an entire line, including whitespace, until a newline, EOF, or size limit is reached.
  • Prevents buffer overflow by limiting the number of characters read, making it safer than gets().
C
#include <stdio.h>

int main() {
    char buff[100];

    printf("Enter a string:\n");

    // Read input from the user
    fgets(buff, sizeof(buff), stdin);

    printf("You entered: %s", buff);

    return 0;
}

Input

This is Geeks

Output

Enter a string:
This is Geeks
You entered: This is Geeks

Explanation : The fgets() function reads one line of text from stdin and stores it in the character array buff. It continues reading until a newline character (\n), the end of the file (EOF), or the buffer limit is reached. The input is automatically null-terminated, making it safer than gets().

Syntax

fgets(buff, n, stream);

Parameters:

  • buff: Pointer to the string buffer where the input will be stored.
  • n: The maximum number of characters to read (including the null terminator).
  • stream: The input stream, typically stdin for reading from the keyboard.

Return Value:

  • Returns the pointer to buff if successful.
  • Returns NULL if an error occurs or the end-of-file (EOF) is reached.

Examples of fgets()

The following examples demonstrate how to use the fgets() function in C programs:

Reading from a File

C
#include <stdio.h>

int main() {
    FILE *fptr = fopen("in.txt", "r");
    
    // Reading the file data using fgets() in the
    // form of a block of size 30 bytes
    char buff[30];
    fgets(buff, sizeof(buff), fptr);
    printf("%s", buff);

    fclose(fptr);
    return 0;
}

Assume that in.txt contains the following data:

The quick brown fox jumps
over the lazy dog.
This sentence contains all letters
of English Alphabets.

Output

The quick brown fox jumps

Reading from Keyboard ( User Input )

C
#include <stdio.h>
#include <string.h>

int main() {
    char name[20];
    
    printf("Enter your name: \n");
    fgets(name, sizeof(name), stdin);
    
    printf("Hello, %s", name);
    return 0;
}

Output

Enter your name: 
Abhishek //Entered by user
Hello, Abhishek

gets() vs fgets()

Following table lists the primary differences between the gets() and fgets() functions:

Aspectgets()fgets()
Buffer Size ControlNo size control so may lead to buffer overflow.Allows size control preventing buffer overflow.
Newline HandlingDiscards newline character.Retains newline character.
Input SourceCan read from stdin only.Can read from any input stream including stdin.
Error HandlingCannot detect errors or EOF so no way to handle read failures.Returns NULL on error or EOF so can handle read failure efficiently.
StatusDeprecated in C11 and later.Recommended and widely used.
Comment