Name | Description | Notes | Source | Availability | |||||||
---|---|---|---|---|---|---|---|---|---|---|---|
fgets() |
Input line of characters | (·) | <stdio.h> |
C89 | C90 | C95 | C99 | C11 | |||
fgetws() |
Input line of wide characters | (·) | <wchar.h> |
C95 | C99 | C11 | |||||
gets() |
Input line of characters from standard input | (·) | <stdio.h> |
C89 | C90 | C95 | C99 | ||||
gets_s() |
Input line of characters from standard input | ? | (·) | <stdio.h> |
C11 |
Parsing with scanf
or similar is error-prone, as it can
be difficult to determine whether input has been properly
read and, if it has failed, to recover the input to try an
alternative. It is recommended to read input for parsing a
line at a time into a buffer, and then attempt to parse the
buffer with sscanf
, strtok
, or similar. The
following functions can be used to read stream upto the end of a
line:
#include<stdio.h>
char *fgets(char *buf, int sz, FILE *str); char *gets(char *buf); #include<wchar.h>
wchar_t *fgetws(wchar_t *buf, int sz, FILE *str);
#define __STDC_WANT_ 1 #includeLIB_ EXT1__ <stdio.h>
char *gets_s(char *buf, rsize_t sz);
fgets
,
gets
and gets_s
read from a byte-oriented stream into a buffer of
char
, while
fgetws
reads from a wide-oriented stream into a buffer of
wchar_t
. fgets
and fgetws
read from the stream str
, while
gets
and gets_s
read from stdin
.
All functions read into a buffer starting at buf
. fgets
,
fgetws
and gets_s
require a buffer of at least sz
elements. gets
just assumes that the buffer is always big enough, and risks
buffer overflow if the input cannot be checked beforehand.
Therefore, never use gets
!
It is so bad that C11 has
dropped it!
All functions read and consume characters until end-of-file
or a newline is encountered, and terminate the string stored
in the buffer with a null character. If fgets
or fgetws
encounters a newline, they add it to the string. gets
and gets_s
discard the newline.
The functions return NULL
if they failed to
read any characters before end-of-file was encountered, or if
they suffer a read error. fgetws
also fails if there is an encoding error. gets_s
additionally fails if sz
is zero or
greater than RSIZE_
. It also
writes a null character into buf[0]
when it fails. [But if sz
is zero, it's not safe to write into the buffer
at all. An error in the spec?]