gtpc2m3l | C/C++ Language Support User's Guide |
These functions read a character from an input stream.
Format
#include <stdio.h> int getc(FILE *stream); int getchar(void);
These functions read 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 getc and fgetc functions are identical. However, getc and getchar functions are provided in a highly efficient macro form. For performance purposes, it is recommended that the macro forms be used rather than the functional forms or fgetc. By default, stdio.h provides the macro versions of these functions.
However, to get the functional forms, do one or more of the following:
The getc and getchar functions have the same restriction as any read operation for a read immediately following a write or a write immediately following a read. Between a write and a subsequent read, there must be an intervening flush or reposition. Between a read and a subsequent write, there must be an intervening reposition unless an EOF has been reached.
Normal Return
The getc and getchar functions return the character read.
Error Return
A returned value of EOF indicates either an error or an EOF condition has occurred. If a read error occurs, the error indicator is set. If an EOF is encountered, the EOF indicator is set.
Use ferror or feof functions to determine whether an error or an EOF condition occurred.
Examples
The following 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; /* 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()) &xclm.= EOF) && ( ch !='\n' ); ++i ) buffer[i] = ch; buffer[i] = '\0'; /* a string should always end with '\0' * printf( "The string is %s\n", buffer ); }
Related Information
See Appendix E, Programming Support for the TPF File System for more information about TPF File System C Functions.