fgets()
Reads a line safely into a buffer (up to size-1 chars).
char *fgets(char *buffer, int size, FILE *stream);This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Reads a line safely into a buffer (up to size-1 chars).
fgets() is the standard and secure function for reading strings from a file stream in C, designed to prevent the buffer overflow vulnerabilities associated with gets(). It reads at most (size - 1) characters from the specified stream and stores them into the buffer. Reading stops if a newline character is encountered or the end-of-file (EOF) is reached. Unlike many other input functions, fgets() includes the newline character in the buffer if it was read, and it always appends a null terminator (\0) at the end. This makes it highly predictable but often requires a post-processing step to trim the newline. From a performance standpoint, fgets() is efficient because it operates on buffered streams (FILE*), minimizing expensive system calls. However, if the input line is longer than the buffer, the remaining characters remain in the input stream, which can cause logic errors in subsequent input operations. It returns the buffer pointer on success or NULL on EOF or error.
Quick reference
Syntax
char *fgets(char *buffer, int size, FILE *stream);
Inputs
Parameters
See it in practice
Examples
Safe Keyboard Input
#include <stdio.h>
int main() {
char buffer[32];
printf("Enter your name: ");
if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
printf("Input received: %s", buffer);
}
return 0;
}Enter your name: Alice Input received: Alice
Reads up to 31 characters from standard input plus a null terminator. The newline from pressing Enter is kept in the buffer.
Removing the Trailing Newline
#include <stdio.h>
#include <string.h>
int main() {
char city[50];
printf("Enter city: ");
fgets(city, sizeof(city), stdin);
city[strcspn(city, "\n")] = '\0';
printf("You live in: [%s]", city);
return 0;
}Enter city: London You live in: [London]
Uses strcspn to find the index of the newline character and replaces it with a null terminator to clean the string for comparison or printing.
Reading a File Line-by-Line
#include <stdio.h>
int main() {
FILE *file = fopen("test.txt", "r");
char line[128];
if (file == NULL) return 1;
while (fgets(line, sizeof(line), file)) {
printf("Line: %s", line);
}
fclose(file);
return 0;
}Line: First line of text Line: Second line of text
Iterates through a file until fgets returns NULL (EOF), processing one line (up to 127 chars) per iteration.
Debug faster
Common Errors
LogicError
Cause: Forgetting that the newline character is stored in the buffer, which causes string comparisons (like strcmp) to fail.
Fix: Manually strip the newline character using strcspn() or by checking the last character before processing.
char buf[10]; fgets(buf, 10, stdin); if(strcmp(buf, "admin") == 0) // Fails because buf is "admin\n"RuntimeError
Cause: Providing an incorrect size argument that is larger than the actual allocated memory of the buffer.
Fix: Always use the sizeof() operator for stack-allocated arrays or pass the exact allocated size for heap-allocated memory.
char small[5]; fgets(small, 100, stdin); // Buffer overflow if input > 4 charsRuntime support
Compatibility
stdio.h; safer than scanf for reading strings
Source: MDN Web Docs
Common questions
Frequently Asked Questions
Reads a line safely into a buffer (up to size-1 chars).
buffer: Destination buffer for the text. size: Buffer size (max chars to read + null). stream: Input stream (often stdin).
LogicError: Manually strip the newline character using strcspn() or by checking the last character before processing. RuntimeError: Always use the sizeof() operator for stack-allocated arrays or pass the exact allocated size for heap-allocated memory.