Go to the previous, next section.
This section describes functions for performing character- and line-oriented input. These functions are declared in the header file `stdio.h'.
Function: int fgetc (FILE *stream)
This function reads the next character as an unsigned char
from
the stream stream and returns its value, converted to an
int
. If an end-of-file condition or read error occurs,
EOF
is returned instead.
Function: int getc (FILE *stream)
This is just like fgetc
, except that it is permissible (and
typical) for it to be implemented as a macro that evaluates the
stream argument more than once. getc
is often highly
optimized, so it is usually the best function to use to read a single
character.
The getchar
function is equivalent to getc
with stdin
as the value of the stream argument.
Here is an example of a function that does input using fgetc
. It
would work just as well using getc
instead, or using
getchar ()
instead of fgetc (stdin)
.
int y_or_n_p (const char *question) { fputs (question, stdout); while (1) { int c, answer; /* Write a space to separate answer from question. */ fputc (' ', stdout); /* Read the first character of the line. This should be the answer character, but might not be. */ c = tolower (fgetc (stdin)); answer = c; /* Discard rest of input line. */ while (c != '\n') c = fgetc (stdin); /* Obey the answer if it was valid. */ if (answer == 'y') return 1; if (answer == 'n') return 0; /* Answer was invalid: ask for valid answer. */ fputs ("Please answer y or n:", stdout); } }
Function: int getw (FILE *stream)
This function reads a word (that is, an int
) from stream.
It's provided for compatibility with SVID. We recommend you use
fread
instead (see section Block Input/Output).
Go to the previous, next section.