C fgetc function reads next character from the stream
Syntax
C fgetc function has the following format.
int fgetc(FILE *stream);
Header
C fgetc function is
from header file stdio.h
.
Description
C fgetc function gets the next character from the stream and increments the file position pointer.
C fgetc function returns EOF: if the end of the file is reached.
When working with binary files
- use
feof()
to check for the end of the file. - use
ferror()
to check for file errors.
Example
Use C fgetc function to read character from stream.
#include <stdio.h>
#include <stdlib.h>
//w w w .jav a 2s . c o m
int main(int argc, char *argv[])
{
FILE *fp;
char ch;
if((fp=fopen("test","r"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
while((ch=fgetc(fp)) != EOF) {
printf("%c", ch);
}
fclose(fp);
return 0;
}
Example 2
#include <stdio.h>
int main ()// ww w .ja v a 2 s .c om
{
FILE * file;
char c;
int n = 0;
file=fopen ("my.txt","r");
if (file==NULL) {
perror ("Error reading my.txt");
}else{
do {
c = fgetc (file);
if (c == '$')
n++;
} while (c != EOF);
fclose (file);
printf ("File contains %d $.\n",n);
}
return 0;
}