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.

Categorystdio.h I/O
KindLibrary function
Header<stdio.h>
C standardC89 / C90

📝 Syntax

char *fgets(char *str, int n, FILE *stream);

⚙️ Parameters

str RequiredA writable character array that receives the text.
n RequiredThe maximum number of characters written, including the null terminator; it must not exceed the array capacity.
stream RequiredAn 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏