getc() – getchar() — Read a Character
Format
#include <stdio.h>
int getc(FILE *stream);
int getchar(void);
Language Level
ANSI
Threadsafe
No
#undef getc
or #undef getchar
allows
the getc
or getchar
function to
be called instead of the macro version of these functions. The functions
are threadsafe.Description
The getc()
function
reads a single character from the current stream position
and advances the stream position to the
next character. The getchar()
function
is identical to getc(stdin)
.
The difference between the getc()
and fgetc()
functions
is that getc()
can
be implemented so that its arguments can be evaluated multiple times.
Therefore, the stream argument to getc()
should
not be an expression with side effects.
Return Value
The getc()
and getchar()
functions
return the character read. A return value of EOF indicates
an error or end-of-file condition. Use ferror()
or feof()
to determine
whether an error or an end-of-file condition occurred.
The value of errno can be set to:
- Value
- Meaning
- EBADF
- The file pointer or descriptor is not valid.
- ECONVERT
- A conversion error occurred.
- EGETANDPUT
- An illegal read operation occurred after a write operation.
- EIOERROR
- A non-recoverable I/O error occurred.
- EIORECERR
- A recoverable I/O error occurred.
The getc()
and getchar()
functions
are not supported in record mode.
Example
This example gets a line of input
from the
stdin
stream.
You can also use getc(stdin)
instead of getchar()
in
the for statement to get a line of input from stdin
. #include <stdio.h>
#define LINE 80
int main(void)
{
char buffer[LINE+1];
int i;
int ch;
printf( "Please enter string\n" );
/* Keep reading until either:
1. the length of LINE is exceeded or
2. the input character is EOF or
3. the input character is a new-line character
*/
for ( i = 0; ( i < LINE ) && (( ch = getchar()) != EOF) &&
( ch !='\n' ); ++i )
buffer[i] = ch;
buffer[i] = '\0'; /* a string should always end with '\0' ! */
printf( "The string is %s\n", buffer );
}