The Wayback Machine - https://web.archive.org/web/20250127001717/https://www.geeksforgeeks.org/fgets-function-in-c/
Open In App

fgets() in C

Last Updated : 14 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C, fgets() is a built-in function that reads the given number of characters of a line from input stream and stores it into the specified string. It stops when it reads either given number of characters, the newline character, or the end-of-file (EOF) is reached.

Let’s take a look at an example:

C
#include <stdio.h>

int main() {
    char buff[100];  
    int n = 10;
  
    printf("Enter a string: ");
  
    // 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 G

Explanation: In this program, fgets() reads 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 of fgets()

fgets() is defined inside <stdio.h> header file.

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.

Then the output will be:

The quick brown fox jumps

Removing the Last Newline Character in fgets()

Since fgets() includes the newline character when the user presses “Enter,” you may want to remove it manually:

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

int main() {
    char name[20];
    
    printf("Enter your name: ");
    fgets(name, sizeof(name), stdin);
    
    // Remove newline character if present
    // Replace newline with null terminator
    name[strcspn(name, "\n")] = '\0'; 
    
    printf("Hello, %s", name);
    return 0;
}


Output

Enter your name: Abhishek (entered by user)
Hello, Abhishek

In this example, strcspn() is used to find the position of the newline character and replace it with a null terminator.

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.

C fgets() Function – FAQs

What happens if the input exceeds the buffer size in fgets()?

If the input length exceeds n-1 characters, fgets() stops reading at n-1 characters, leaving the remaining input in the buffer. This leftover input can be read in subsequent calls to fgets().

Why is the string read by fgets() sometimes smaller than given size?

If the input is shorter than n-1 or ends with a newline, the resulting string will appear smaller.

Why prefer fgets() over other input functions?

fgets() is widely regarded as a safer alternative for reading strings in C, especially compared to functions like gets() that have been deprecated. Here’s why:

  • Buffer Overflow Protection: fgets() allows you to specify the maximum number of characters to read ensuring that the function doesn’t write beyond the allocated memory of the buffer.
  • Null-Termination Guarantee: fgets() ensures that the resulting string is null-terminated preventing undefined behaviour when using string-handling functions.
  • Flexibility with Streams: It can read from any input stream, such as files or stdin, making it suitable for various input scenarios.

How should I handle errors o fgets()?

fgets() returns the pointer to the buffer (str) on success. If an error occurs or EOF is reached before any characters are read, it returns NULL. Always check the return value of fgets() to handle errors or end-of-file scenarios.



Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg