The getc
function in C reads the next character from any input stream and returns an integer value. It is a standard function in C and can be used by including the <stdio.h>
header file.
int getc(FILE *stream)
stream
: A file stream or standard input stream identified by a pointer to the FILE object.int
: Integer casting of the character read by getc
. If the read operation is unsuccessful due to an error or the end of a file is reached, EOF
is returned.#include <stdio.h>int main() {char c;printf("Enter a character: ");c = getc(stdin);printf("\nCharacter is: %c", c); // prints the character on standard output, /n is used to add a newlinereturn 0;}
Enter the input below
In the code example above, the user is prompted for a character from standard input, and the value entered is read by the getc
function. The value read is then stored in the c
variable and displayed.
#include <stdio.h>int main() {FILE *fp = fopen("sample.txt","r"); //file pointer opens the file in read modeprintf("Character read from file is: %c", getc(fp)); //file content is: educativereturn 0;}
In the example above, the sample.txt
file is opened in read mode. The position pointed to by the file pointer (fp
) is retrieved through getc
and displayed.
Free Resources