fgetc in C Programming

The C fgetc function used to read/return the character(s) from the specified stream at the current position in a file and then increments the pointer position.

How to read the character, or character array, or string data from the Files using fgetc in C Programming with example?. This fgetc function reads character by character, but you can use fgets function to read complete string at one stretch.

Syntax of fgetc in C Programming

The syntax behind the fgetc in C Programming language is as shown below.

int fgetc(FILE *stream)

or we can write it as:

int getc(<File Pointer>)

From the above fgetc function code snippet,

  • stream: Please specify the pointer to a FILE object, or say, file pointer that holds the file address and the operation mode

We are going to use the following specified file to demonstrate this C fgetc function.

FGETC in C Programming 1

From the above screenshot, you can observe that the sample.txt file is in our C File Examples folder. And it contains text as Tutorial Gateway.

fgetc in C Programming Example

The fgetc method used to read the character(s) from the user-specified file and returns the output. This program for fgetc in c will help you to understand the same.

TIP: You have to include the #include<stdio.h> header before using this c fgetc function.

// C fgetc function example
#include <stdio.h> 

int main()
{
   FILE *fileAddress;
   fileAddress = fopen("sample.txt", "r");
   char ch;
	
   if (fileAddress != NULL) {
	// Check whether it is the last character or not
	while (!feof(fileAddress)) {
		ch = fgetc(fileAddress);
		//printf("%c", ch);
		printf("Character we are reading from the File = %c \n", ch);
	}
	fclose(fileAddress);		
   }
   else {
	printf("\n Unable to Create or Open the Sample.txt File");
   }
   return 0;
}
FGETC in C Programming 2

In this fgetc in c example, first, we created the File pointer and then assigned the file in read mode because we want to read the characters present in the sample.txt. Please refer to fgets function article.

TIP: In this C program, we haven’t mentioned the full path of file name because my .c application and the text file reside in the same location. If your scenario is different then, please provide the full path.

FILE *fileAddress;
fileAddress = fopen("sample.txt", "r");

The following If Statement check whether we successfully opened the sample.txt file or not.

if (fileAddress != NULL) {

Next, we used the While Loop to traverse each character present in the sample.txt. Within the while loop, we used the condition to check whether the compiler reached to the file end or not.

while (!feof(fileAddress)) {

Next, we used the fgetc function to read every character present in the sample.txt file and assigning the same to ch character that we initialized before.

ch = fgetc(fileAddress);

Here, we are closing the C programming file pointer.

fclose(fileAddress);