- Fgets
fgets is a function in
C programming language that reads a string of characters with a specific length from a given file stream source. As far as traceable,fgets
stands for "file get string". It is included in theC standard library header file
.stdio.h The
fgets
function terminates reading after a new-line character is found. 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. The prototype of the function is as follows::char* fgets(char *string, int length, FILE * stream)
The stream argument specifies from which stream will the string be read from.
stdin
is commonly used here, for reading from the standard input. Otherwise, aFILE *
value returned by thefopen function is used.ample 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 LINE_MAX (generally found in limits.h) is often used to size the character buffer.Limitations
The fixed buffer size imposed by fgets() is cumbersome in applications which need to handle arbitrarily long lines of text.
GNU libc provides a function called getline(), which will read an entire line, reallocating the buffer if it is not long enough. [http://www.gnu.org/software/libc/manual/html_node/Line-Input.html#index-getline-993]
Advanced applications can avoid buffer limitations by using
mmap .ee also
*
scanf
*gets
Wikimedia Foundation. 2010.