gets(), puts() & fgets()
Beyond printf and scanf, C's standard library offers a few simpler, line-oriented functions for reading and writing whole lines of text at once. One of them — gets — is so dangerous it was removed from the language standard entirely, and understanding why is itself a valuable lesson in C's approach to safety.
puts() — simple line output
puts writes a string followed by a newline. It's simpler than printf when you just need to print a fixed string with no formatting:
#include <stdio.h>
int main(void) {
puts("Hello, World!"); /* automatically appends '\n' */
puts("Goodbye!");
return 0;
}Hello, World! Goodbye!
gets() — removed from the language for good reason
char buffer[10];
gets(buffer); /* DO NOT DO THIS -- if the user types more than 9 characters,
gets() happily writes past the end of buffer */fgets() — the safe, modern replacement
fgets reads a line, but takes a maximum size so it can never write past the end of your buffer. Its signature is char *fgets(char *str, int n, FILE *stream) — it reads at most n - 1 characters, always leaving room for the null terminator, and stops early if it hits a newline or end-of-file.
#include <stdio.h>
#include <string.h>
int main(void) {
char buffer[32];
printf("Enter your name: ");
if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
/* fgets keeps the trailing newline if it fits -- strip it */
size_t len = strlen(buffer);
if (len > 0 && buffer[len - 1] == '\n') {
buffer[len - 1] = '\0';
}
printf("Hello, %s!\n", buffer);
}
return 0;
}At a glance
Function | Bounds-checked | Keeps the newline | Status |
|---|---|---|---|
| No | No (discards it) | Removed in C11 -- never use |
| Yes (you supply the size) | Yes, if it fits | Recommended for reading lines |
| No (unless you specify a width like | N/A -- stops at whitespace | Use with an explicit width, or avoid for untrusted input |