fgetc in C Programming

The C fgetc function is 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, character array, or string data from the Files using fgetc in C Programming with an example? This fgetc function reads character by character, but you can use the fgets function to read a complete string at one stretch.

Syntax of fgetc in C Programming

The syntax behind the fgetc in this 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, a file pointer that holds the address and the operation mode

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

Sample Text File 1

The above screenshot shows that the sample.txt file is in our File Examples folder. And it contains text as Tutorial Gateway.

fgetc in C Programming Example

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

TIP: You have to include the #include<stdio.h> header before using this 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 the reading mode because we wanted to read the characters present in the sample.txt. Please refer to the fgets function article.

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

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

The following If Statement checks whether we successfully opened the sample.txt 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 the end or not.

while (!feof(fileAddress)) {

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

ch = fgetc(fileAddress);

Here, we are closing the C programming file pointer.

fclose(fileAddress);