C Reference ยท stdio.h
C fgets() function
Reference for C fgets(): read a line into a fixed-size buffer without overflow, keep or strip the newline, detect truncated lines and handle EOF correctly.
fgets() reads characters from a stream into a buffer until it has read a newline, hit the end of the file, or filled the buffer (leaving room for the terminating null character). It never writes past the size you give it, which is exactly why it replaced the removed gets().
The newline is kept in the buffer when there was room for it. That detail drives most of the real-world code around fgets(): stripping the newline, and noticing when a line was too long to fit.
#include <stdio.h> char *fgets(char *restrict buf, int size, FILE *restrict stream);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
char *fgets(char *restrict buf, int size, FILE *restrict stream);
| Name | Description |
|---|---|
buf |
Destination array. It receives the characters read plus a terminating '\0'. |
size |
The total size of buf in bytes. At most size - 1 characters are read. |
stream |
An open input stream: stdin or a file opened for reading. |
Returns: buf on success. NULL if the end of the file was reached before any character was read, or if a read error occurred.
Errors / undefined behavior: a buf that is smaller than size claims, or a NULL or closed stream, is undefined behavior. When NULL is returned because of an error, the contents of buf are indeterminate, so do not use them. If end-of-file occurs after some characters were read, fgets() returns buf normally and the next call returns NULL.
Usage notes
- Check for
NULL, notfeof(). The loopwhile (fgets(...) != NULL)is the correct pattern. Testingfeof()before reading processes the last line twice (seefeofandferror). - Use
sizeof buf. Pass the real array size, not a magic number. This works whenbufis an array in the same scope; for achar *parameter you must pass the size separately. - Removing the newline.
buf[strcspn(buf, "\n")] = '\0';is a compact, safe idiom that works whether or not a newline is present. Do not usebuf[strlen(buf) - 1] = '\0': it fails on an empty string and chops a real character from a line without a newline. - Detecting a long line. If the buffer holds no
'\n'and you did not reach the end of the file, the line was cut short. The rest is still in the stream and the next call returns it. Either grow the buffer or discard the rest with agetchar()loop. - Embedded null characters.
fgets()cannot tell you that the input had a'\0'; the string ends at the first one, andstrlen()will under-report the line. Usefread()or POSIXgetline()for binary input. - Size 1 or less.
size == 1stores only the terminator;size <= 0is not meaningful. Always give a buffer of at least 2 bytes. - Interaction with
scanf. Afterscanf("%d", &n)a leftover newline makes the nextfgets()return an empty line. Read everything withfgets()and parse withsscanf()orstrtol()to avoid this. - Windows line endings. A text file with
\r\nread in binary mode leaves the'\r'in the buffer. On POSIX systems no translation is done at all. - Complexity: linear in the number of characters read.