How to fgets in c
Content on WhatAnswers is provided "as is" for informational purposes. While we strive for accuracy, we make no guarantees. Content is AI-assisted and should not be used as professional advice.
Last updated: April 4, 2026
Key Facts
- Reads up to `n-1` characters from a stream.
- Stops reading at a newline character (`\n`).
- Includes the newline character in the buffer if read.
- Always null-terminates the buffer.
- Returns `NULL` on end-of-file or error.
What is `fgets()` in C?
The `fgets()` function is a standard C library function, declared in the <stdio.h> header. Its primary purpose is to read a string from a given input stream and store it into a character array (buffer). Unlike some other input functions, `fgets()` is generally considered safer because it prevents buffer overflows by limiting the number of characters it reads.
How does `fgets()` work?
The syntax for `fgets()` is as follows:
char *fgets(char *str, int n, FILE *stream);str: This is a pointer to the character array (buffer) where the read string will be stored.n: This is the maximum number of characters to read, including the null terminator. `fgets()` will read at mostn-1characters from the stream.stream: This is a pointer to aFILEobject that identifies the input stream. Common streams includestdin(standard input, usually the keyboard),stdout(standard output, usually the console), and file streams opened usingfopen().
The function reads characters from the specified stream and stores them into str until one of the following conditions is met:
n-1characters have been read.- A newline character (
'\n') is encountered. The newline character is read and stored in the buffer. - End-of-file (EOF) is reached.
After reading, `fgets()` appends a null terminator ('\0') to the end of the string in the buffer, making it a valid C string.
Return Value
The return value of `fgets()` indicates its success or failure:
- On success, it returns a pointer to the buffer
str. - If an error occurs during reading, or if the end-of-file is reached before any characters are read, it returns
NULL.
It's crucial to check the return value of `fgets()` to handle potential errors or the end of input gracefully.
Key Differences from `gets()`
The `gets()` function was a predecessor to `fgets()` but is now deprecated and should never be used. The primary danger of `gets()` is that it reads until a newline or EOF is encountered without any limit on the number of characters. This makes it highly susceptible to buffer overflow vulnerabilities, where an attacker could provide input longer than the buffer, overwriting adjacent memory and potentially crashing the program or executing malicious code. `fgets()` mitigates this risk by accepting the buffer size as an argument.
Example Usage
Here's a simple example demonstrating how to use `fgets()` to read input from the keyboard:
#include <stdio.h>int main() {char buffer[100]; // Declare a buffer of size 100printf("Enter a string: ");// Read up to 99 characters from stdin into bufferif (fgets(buffer, sizeof(buffer), stdin) != NULL) {printf("You entered: %s", buffer); // Note: buffer may contain a newline// Optional: Remove trailing newline if present// size_t len = 0;// while (buffer[len] != '\n' && buffer[len] != '\0') {// len++;// }// if (buffer[len] == '\n') {// buffer[len] = '\0';// }// printf("Cleaned input: %s\n", buffer);} else {printf("Error reading input or end of file reached.\n");}return 0;}In this example, sizeof(buffer) is passed as the size limit to `fgets()`. This ensures that even if the user types more than 99 characters, `fgets()` will not write past the allocated memory for buffer, preventing a buffer overflow. The output might include a trailing newline character if the user pressed Enter and there was space in the buffer.
Handling the Trailing Newline
A common characteristic of `fgets()` is that it includes the newline character ('\n') in the buffer if it's read before the size limit is reached. Often, this newline is not desired in the processed string. You can remove it by finding its position and replacing it with the null terminator:
#include <stdio.h>#include <string.h> // For strcspnint main() {char buffer[100];printf("Enter text: ");if (fgets(buffer, sizeof(buffer), stdin) != NULL) {// Remove trailing newline character, if anybuffer[strcspn(buffer, "\n")] = 0;printf("Processed input: %s\n", buffer);} else {printf("Input error.\n");}return 0;}The strcspn() function finds the length of the initial segment of the string which consists entirely of characters NOT in the specified reject string (in this case, "\n"). If a newline is found, its index is returned, and we overwrite it with a null terminator. If no newline is found (e.g., the input was longer than the buffer minus one character), strcspn() returns the index of the null terminator, and overwriting it with 0 has no effect.
Reading from Files
`fgets()` is also excellent for reading data line by line from files:
#include <stdio.h>int main() {FILE *file_ptr;char buffer[256];file_ptr = fopen("my_data.txt", "r"); // Open file for readingif (file_ptr == NULL) {perror("Error opening file");return 1;}printf("Reading from file:\n");// Read lines until end of filewhile (fgets(buffer, sizeof(buffer), file_ptr) != NULL) {// Process each line (e.g., print it)printf("%s", buffer);}fclose(file_ptr); // Close the filereturn 0;}This example opens a file named my_data.txt, reads it line by line using `fgets()`, and prints each line to the console. Remember to handle potential file opening errors and always close the file using `fclose()` when you are done with it.
Conclusion
`fgets()` is a fundamental and safer way to read string input in C compared to older functions like `gets()`. By specifying the buffer size, it provides crucial protection against buffer overflows. Understanding how it handles newlines and its return values is key to using it effectively for both standard input and file operations.
More How To in Daily Life
Also in Daily Life
More "How To" Questions
Trending on WhatAnswers
Browse by Topic
Browse by Question Type
Sources
- fgets - WikipediaCC-BY-SA-4.0
- Reading Lines of Text - GNU C Library ManualCC-BY-SA-4.0
- fgets - C++ ReferenceCC-BY-SA-4.0
Missing an answer?
Suggest a question and we'll generate an answer for it.