The syntax of the
fgetc() functon is:
int fgetc(FILE *fp);
This function is complementary to
fputc() function. It reads a single character from the file and increments the file position pointer. To use this function file must be opened in read mode. On success, it returns the ASCII value of the character but you can also assign the result to a variable of type
char. On failure or end of file, it returns
fputc() this function uses buffer memory too. So instead of reading a single character from the file one by one, a whole block of characters from the file is read into the buffer. The characters are then handed over one at a time to the function
fgetc(), until the buffer is empty. If there are still some characters left to read in the file then again a block of characters is read into the buffer.
The following program demonstrates how to use
fp = fopen("myfile.txt", "r");
if(fp == NULL)
printf("Error opening file\n");
printf("Reading contents of myfile.txt: \n\n");
while( (ch=fgetc(fp)) != EOF )
printf("%c", ch, ch);
Reading contents of myfile.txt:
Testing fputc() function
How it works:
In line 6, a variable
ch of type
int is declared.
In line 7, a structure pointer variable
fp of type
struct FILE is declared.
In line 8,
fopen() function is called with two arguments namely
"r" . On success, it returns a pointer to file
"myfile.txt" and opens the file
"myfile.txt" in read-only mode. On failure or end of file, it returns
In line 10, if statement is used to test the value of
fp. If it is
printf() statement prints the error message and program terminates. Otherwise, the program continues with the statement following the if statement.
In line 16,
printf() statement prints
"Reading contents of myfile.txt: \n\n" to the console.
In lines 18-21, a while loop is used to read characters one by one from the file and prints it to the console using
printf() statement (you can also use putchar() function). The parentheses around
ch = fgetc(fp) is necessary because the precedence of
!= operator is greater than that of
In line 23,
fclose() function is used to close the file.