fgets() in C

Last Updated : 18 Oct, 2025

fgets() is a built-in function in <stdio.h> used to read a line of text from input.

  • It stores the input into a character array and stops reading when it reaches a newline character, the specified number of characters, or end-of-file (EOF).
  • It is safer than gets() because it prevents buffer overflow by limiting the number of characters read.
  • We can use it to read a full line (including whitespace) from input, rather than stopping at the first space like scanf("%s", …) would.
C
#include <stdio.h>

int main() {
    char buff[100];  
    int n = 10;
  
    printf("Enter a string: \n");
  
    // Read input from the user
    fgets(buff, n, stdin);
    printf("You entered: %s", buff);
    return 0;
}


Output

Enter a string: 
This is Geeks {entered by user}
You entered: This is Geeks

Explanation : In this program, fgets() reads will read up to 9 characters or until a newline (\n) is encountered from the standard input (stdin) and stores them in the array buff, ensuring it is null-terminated.

Syntax

C
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