0
0
CHow-ToBeginner · 3 min read

How to Use fgets in C: Syntax, Example, and Tips

Use fgets in C to read a line of text from a file or standard input safely by specifying a buffer, its size, and the input stream. It reads until a newline or the buffer limit minus one, adding a null terminator. This prevents buffer overflow unlike gets.
📐

Syntax

The fgets function reads characters from a stream into a buffer until a newline, end-of-file, or the specified limit is reached. It includes the newline character if found and always adds a null terminator.

  • char *fgets(char *str, int n, FILE *stream);
  • str: Pointer to the buffer where the string will be stored.
  • n: Maximum number of characters to read (including the null terminator).
  • stream: Input stream to read from (e.g., stdin for keyboard input).
c
char *fgets(char *str, int n, FILE *stream);
💻

Example

This example shows how to use fgets to read a line from the keyboard and print it. It safely reads up to 49 characters plus the null terminator into the buffer.

c
#include <stdio.h>

int main() {
    char buffer[50];
    printf("Enter a line of text (max 49 chars): ");
    if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
        printf("You entered: %s", buffer);
    } else {
        printf("Error reading input.\n");
    }
    return 0;
}
Output
Enter a line of text (max 49 chars): Hello, fgets in C! You entered: Hello, fgets in C!
⚠️

Common Pitfalls

Common mistakes when using fgets include:

  • Not checking if fgets returns NULL, which means input failed.
  • Forgetting that fgets keeps the newline character if there is space, which may affect string processing.
  • Using a buffer size too small, causing input to be split across multiple reads.

To remove the newline, you can replace it with a null terminator manually.

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

int main() {
    char buffer[10];
    printf("Enter text: ");
    if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
        size_t len = strlen(buffer);
        if (len > 0 && buffer[len - 1] == '\n') {
            buffer[len - 1] = '\0'; // Remove newline
        }
        printf("Processed input: %s\n", buffer);
    }
    return 0;
}
Output
Enter text: Hello Processed input: Hello
📊

Quick Reference

  • Use fgets(buffer, size, stdin) to read input safely.
  • Always check if fgets returns NULL.
  • Remember fgets includes the newline if space allows.
  • Remove newline if you want a clean string.
  • Buffer size includes space for the null terminator.

Key Takeaways

Use fgets to safely read strings with a size limit to avoid buffer overflow.
Always check fgets return value to handle input errors.
Remember fgets keeps the newline character if there is room in the buffer.
Remove the newline manually if you want a clean string without it.
Specify buffer size including space for the null terminator.