fgets() Read a line from a stream
fgets() Read a line from a stream
fgets() reads at most n-1 characters, keeps any newline, and adds a null terminator. It returns str, or NULL if no character is read before EOF or error.
| Category | stdio.h I/O |
|---|---|
| Kind | Library function |
| Header | <stdio.h> |
| C standard | C89 / C90 |
📝 Syntax
char *fgets(char *str, int n, FILE *stream);
⚙️ Parameters
| str Required | A writable character array that receives the text. |
|---|---|
| n Required | The maximum number of characters written, including the null terminator; it must not exceed the array capacity. |
| stream Required | An open stream available for input. |
Returns: Returns str on success, or NULL if end-of-file is encountered before any character is read or if a read error occurs.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
first line
⚠️ Warning n must not exceed the destination capacity and should be positive. After reading at least one character successfully, the function appends a null terminator.
💡 Tip If a newline is read before the limit is reached, it remains in the array; the newline in the example output comes from the input.
🏷️ Related stdio.h functions
📚 Related Tutorials
❓ FAQ
QDoes fgets keep the newline, and how can I remove it?
AIt normally keeps a newline that was read. Find it with p = strchr(line, '\n'), then assign *p = '\0' when p is not NULL.
QWhat happens when the fgets buffer fills before a newline?
AIt returns the portion read so far with a null terminator. The remainder of that line stays in the stream for subsequent reads.
QShould the second fgets argument be the array size or the array size minus one?
APass the actual capacity, not the capacity minus one. For char buf[64], use fgets(buf, 64, stream); the function reads at most 63 characters and then writes a terminator. Passing 65 risks overflow, while passing 63 intentionally reads one fewer character.