getc() - I/O Function
How is "getc()" used in C++?
Explanation
getc() is an I/O function equivalent to fgetc() also expects a stream as parameter, but getc may be implemented as a macro. This function is used to return the next character from the input stream then increases the file position indicator. The character read by this function is a unsigned char which is converted to an integer. If the End-of-File is reached or a reading error occurs the function returns EOF.
Syntax:
int getc (FILE *stream);
Example :
#include <stdio.h> int main() { int c; int count; FILE *stri = fopen("getceg.txt", "r"); while( c != EOF ) { c = getc(stri); if (c == 'A') count++; } fclose(stri); printf ("File contains %dA.\n", count); return 0; } |
Result :
File has the character A 3 times.
In the above example the function is used to get every character of a text file till EOF. A loop is used to find the number of times the char 'A' is found in the file. The content of the text file is "ABCA1@@ABNM".