C getc()
function is a C library function, which reads a character from a file that has been opened in read mode by the fopen()
function. This tutorial guides you on how to use the getc()
function in the C program.
Syntax:
int getc( FILE * stream );
Return Value
getc()
function returns the next requested object from the stream on success.- Character values are returned as an unsigned char cast to an int or
EOF
at the end of the file or error. - The functions
feof()
andferror()
must be used to distinguish between end-of-file and error.
Example:
#include<stdio.h>
int main()
{
FILE *fp = fopen("fileName.txt", "r");
int ch = getc(fp);
while (ch != EOF)
{
//To display the contents of the file on the screen
putchar(ch);
ch = getc(fp);
}
if (feof(fp))
printf("\n Reached the end of file.");
else
printf("\n Something gone wrong.");
fclose(fp);
getchar();
return 0;
}