fgets
get a line from a stream
You're viewing an older version of this page (#3255). View the current version.
NAME
<span class="Nm" id="fgets">fgets</span>, <span class="Nm" id="gets">gets</span>
INTERFACE
#include <stdio.h> char fgets ( char * restrict str, int size, FILE * restrict stream ) char gets ( char *str )
DESCRIPTION
The fgets function reads at most one less than the number of characters specified by \c size from the given \c stream and stores them in the string \c str. Reading stops when a newline character is found, at end-of-file or error. The newline, if any, is retained. If any characters are read and there is no error, a '<span class="Qlq">\\0</span>' character is appended to end the string. \n \n The gets function is equivalent to fgets with an infinite \c size and a \c stream of <span class="Dv">stdin</span>, except that the newline character (if any) is not stored in the string. It is the caller's responsibility to ensure that the input line, if any, is sufficiently short to fit in the string.
RETURN VALUES
Upon successful completion, fgets and gets return a pointer to the string. If end-of-file occurs before any characters are read, they return <span class="Dv">NULL</span> and the buffer contents remain unchanged. If an error occurs, they return <span class="Dv">NULL</span> and the buffer contents are indeterminate. The fgets and gets functions do not distinguish between end-of-file and error, and callers must use reference:feof (3) and ferror (3) to determine which occurred.
ERRORS
<table cellspacing="0" class="refpage" style="margin-left:25px"> <tr> <td valign="top" nowrap> [<span class="Bq"><span class="Er">EBADF</span></span>] </td> <td valign="top"> The given \c stream is not a readable stream. </td> </tr> </table> \n \n The function fgets may also fail and set <span class="Va">errno</span> for any of the errors specified for the routines fflush (3) , reference:fstat (2) , reference:read (2) , or malloc (3) . \n \n The function gets may also fail and set <span class="Va">errno</span> for any of the errors specified for the routine reference:getchar (3) .
SECURITY CONSIDERATIONS
The gets function cannot be used securely. Because of its lack of bounds checking, and the inability for the calling program to reliably determine the length of the next incoming line, the use of this function enables malicious users to arbitrarily change a running program's functionality through a buffer overflow attack. It is strongly suggested that the fgets function be used in all cases. (See the FSA.)
SEE ALSO
reference:feof (3) , ferror (3) , reference:fgetln (3) , reference:fgetws (3)
STANDARDS
The functions fgets and gets conform to