C Programming/stdio.h/fgets

fgets is a function in the C programming language that reads a limited number of characters from a given file stream source into an array of characters. stands for file get string. It is included in the C standard library header file. The prototype of the function is as follows:

The function terminates reading either after a new-line character is found or end-of-file is reached, or after (length - 1) characters have been read. If a new-line was reached it is included in the string as the last character before the null character. The length argument includes space needed for the null character which will be appended to the end of the string. As a result, to read N characters, the length specification must be specified as N+1. The string read is returned if at least one character was read and no error occurred, otherwise a NULL-pointer is returned.

The stream argument specifies the stream from which the string be read. is commonly used here, for reading from the standard input. Otherwise, a  value returned by the   function is used.

Sample usage
The following code reads characters from the console input and prints them out 20 in a line with the puts function until an EOF occurs.

Use in POSIX utilities
For compliance with POSIX utility line lengths, the definition  (generally found in limits.h) is often used to size the character buffer.

Limitations
The fixed buffer size imposed by  is cumbersome in applications which need to handle arbitrarily long lines of text.

POSIX.1-2008-conforming systems provide a function called  (originally a GNU extension ), which will read an entire line, reallocating the buffer if it is not long enough.

Advanced applications can avoid buffer limitations by using mmap.