getc
int getc (FILE * stream); | stdio.h |
cplusplus.com |
Get the next character.
Returns the next character of the stream and increases
the file pointer to point to the next character.
This routine is normally implemented as a macro with the same result as
fgetc().
Parameters.
Return Value.
The character read is returned.
If the End Of File is reached or there has been an error reading,
the function returns an EOF character.
The character is read as unsigned char and
returned as int.
Note that when you work with binary files EOF is a valid character and
you must use feof() function to check if
End Of File has really been reached.
Also EOF can indicate an error while reading, use ferror()
to check if an error has occurred.
Portability.
Defined in ANSI-C.
Example.
/* getc example: money counter */
#include <stdio.h>
main ()
{
FILE * pFile;
char c;
int n = 0;
pFile = fopen("myfile.txt","r");
if (pFile==NULL) perror ("Error opening file");
else
{
do {
c = getc (pFile);
if (c == '$') n++;
} while (c != EOF);
fclose (pFile);
printf ("File contains %d$.\n",n);
}
return 0;
}
This program reads myfile.txt character by character
and uses the n variable to count how many dollar characters
($) does it contain.
See also.
fputc,
fread,
fwrite