fgets in C reads one line from a stream into a character array and never writes more than the size you give it. Call it as fgets(buf, sizeof buf, stdin), check that the result is not NULL, and remember that the newline, if there was room for it, is stored in the buffer.
Syntax
fgets is declared in <stdio.h>:
char *fgets(char *restrict str, int count, FILE *restrict stream);
The three parameters are:
str: the destination array.count: the maximum number of characters to write, including the null terminator. In practice this issizeof buffor a real array.stream: where to read from, such asstdinor aFILE *fromfopen.
Per cppreference, it reads at most count - 1 characters. It stops early after a newline, which is stored in the buffer, or at end-of-file. If any characters were read and no error occurred, it writes '\0' straight after the last character stored, so the result is always a valid C string.
A minimal example: read one line from the keyboard
#include <stdio.h>
int main(void)
{
char name[32];
printf("Name: ");
if (fgets(name, sizeof name, stdin) == NULL) {
fputs("No input.\n", stderr);
return 1;
}
printf("Hello, %s", name);
return 0;
}
Example output when you type Ada and press Enter:
Name: Ada
Hello, Ada
There is no \n in the printf format string, yet the greeting ends with a line break. That is the newline fgets stored in name. It is the first thing that surprises people, and the next section deals with it.
The newline is part of the string
When the user presses Enter, fgets stores the newline as the last character before the terminator. Comparing the buffer with strcmp(name, "Ada") would fail, because the buffer holds "Ada\n". Strip the newline when you need the bare text:
#include <string.h>
name[strcspn(name, "\n")] = '\0';
strcspn returns the length of the initial segment of its first argument that contains none of the characters in its second argument. Here that is the index of the first newline, or the length of the whole string if there is no newline. Overwriting that position with '\0' removes the newline when present and harmlessly rewrites the terminator when it is not. This is a widely used idiom rather than something the standard documents, but it relies only on the documented behavior of strcspn.
Return value: check it every time
The return value tells you whether the buffer is usable.
| Situation | Return value | Buffer contents |
|---|---|---|
| Characters read, no error | str | Valid string, null-terminated |
| End-of-file, some characters read first | str | Valid string; EOF indicator is set |
| End-of-file, nothing read | NULL | Unchanged |
| Read error | NULL | Indeterminate, may not be terminated |
The details come from cppreference and the POSIX specification. On a NULL return, call feof(stream) or ferror(stream) to tell a normal end of input from a failure. POSIX also requires fgets to set errno on a read error. Do not use the buffer after a NULL return: on end-of-file it still holds whatever it held before, so printing it would repeat the previous line.
This is why the standard loop reads like this:
char line[256];
while (fgets(line, sizeof line, stdin) != NULL) {
/* use line */
}
if (ferror(stdin)) {
perror("read failed");
}
The loop ends at end-of-file (Ctrl+D on Linux and macOS, Ctrl+Z then Enter on Windows) or on error, and the check after it separates the two cases.
What happens with a line longer than the buffer
If the line has more than count - 1 characters, fgets stores the first count - 1 of them and stops. The rest of the line is still waiting in the stream, and the next call picks it up. cppreference demonstrates this with an 8-byte buffer reading "Alan Turing\n":
char buf[8];
while (fgets(buf, sizeof buf, tmpf) != NULL)
printf("\"%s\"\n", buf);
Example output, from the cppreference page:
"Alan Tu"
"ring
"
The first call returned seven characters and no newline. The second returned ring plus the newline. So a missing newline in the buffer means one of two things: the line was cut off because it did not fit, or the file ended without a final newline. You can tell them apart by checking the last character:
size_t length = strlen(line);
if (length > 0 && line[length - 1] == '\n') {
line[length - 1] = '\0'; /* complete line */
} else if (!feof(stdin)) {
/* line was truncated: the rest is still in the stream */
}
What you do in the truncated case depends on the program. You can reject the input, read and discard the remainder in a loop until you pass the newline, or switch to a function that grows the buffer for you.
Why not gets
gets(buf) takes no size. It cannot know how big the array is, so a long enough line overwrites memory past the end. The Linux man page opens its description with "Never use this function" and notes that it has been used to break computer security. ISO C11 removed gets from the language entirely, and since glibc 2.16 the headers hide its declaration when _ISOC11_SOURCE is defined. The man page's advice is to use fgets instead.
The same size-blindness applies to scanf("%s", buf) with no field width. If you do want scanf, give it a width one smaller than the array, as in scanf("%31s", name) for a 32-byte array. Note that %s stops at whitespace, so it reads a word, not a line, which is the main reason people reach for fgets in the first place.
Edge cases
- Count of 1 or less. The standard is unclear about these values. cppreference reports that implementations differ for
count == 1and do nothing and report an error forcount < 1. Always pass at least 2. - Passing a pointer instead of an array.
sizeofonly gives the buffer size for a real array in scope. Ifbufis achar *parameter,sizeof bufis the size of the pointer, usually 8 bytes on 64-bit systems. Pass the length separately in that case. The basics of arrays and pointers are covered in Pointers in C Explained With Examples. - Embedded null bytes.
fgetsdoes not report how many characters it read. If the input may contain'\0',strlenwill stop early and you cannot recover the true length. Usegetlineorfreadfor binary-like data. - Mixing with scanf. After
scanf("%d", &n), the newline the user typed is still in the stream, so the nextfgetsreturns an empty line immediately. Read numbers withfgetstoo, then convert withstrtolorsscanf.
Reading a whole file line by line
The same loop works for files. Open the file, read until NULL, and close it:
#include <stdio.h>
int main(void)
{
FILE *file = fopen("notes.txt", "r");
char line[256];
unsigned number = 0;
if (file == NULL) {
perror("notes.txt");
return 1;
}
while (fgets(line, sizeof line, file) != NULL) {
number++;
printf("%u: %s", number, line);
}
fclose(file);
return 0;
}
Because the loop prints each line with its stored newline, no extra line breaks are needed. The last line of a file that has no trailing newline is printed without one, so the shell prompt appears right after it. If you use a counter in a for loop instead, see For Loop in C: Syntax, Examples, break and continue, though a while loop fits this job better because the number of lines is not known in advance.
When to use getline instead
If lines can be arbitrarily long, a fixed buffer will always force a decision about truncation. On POSIX systems, getline removes that problem. It takes a pointer to a buffer pointer and a size, allocates or reallocates the buffer as needed, and returns the number of characters read, or -1 at end-of-file or on error:
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *line = NULL;
size_t capacity = 0;
while (getline(&line, &capacity, stdin) != -1) {
/* use line */
}
free(line);
return 0;
}
Per the Linux man page, the buffer includes the newline if one was found, and the caller must free it, even if the call failed. getline is POSIX, not part of ISO C, so it is not guaranteed on every compiler. On glibc it needs _POSIX_C_SOURCE set to 200809L or higher, which is why the define sits at the top of the example. For portable code, or for fixed-size fields where a limit is natural, fgets remains the standard choice.
Frequently asked questions
- What does fgets do in C?
- fgets reads characters from a stream into a char array. It stops after at most count minus 1 characters, after a newline (which it keeps in the buffer), or at end-of-file, and then writes a null terminator after the last character stored.
- Does fgets keep the newline?
- Yes. If the line fits in the buffer, the newline is stored before the null terminator. If the line is too long, the buffer holds the first part of the line with no newline, and the rest stays in the stream for the next call.
- How do I remove the newline from fgets input?
- A common idiom is buf[strcspn(buf, "\n")] = '\0'; from <string.h>. If there is no newline, strcspn returns the string length and the assignment just rewrites the existing terminator.
- Why should I use fgets instead of gets?
- gets has no way to know the size of the buffer, so it keeps writing past the end of the array when the line is long. ISO C11 removed it from the language. fgets takes the buffer size and never writes more than that.
- What does fgets return at end of file?
- It returns a null pointer when the end of the file is reached before any character is read, and the buffer is left unchanged. If some characters were read before end-of-file, it returns the buffer pointer as normal.