How to use fgetc in C Programming

how to use fgetc in c

The fgetc() function read a single character from the stream and return their ASCII value. After reading the character, it advances the associated file position indicator for the stream. It takes only one argument file stream.

In this article, I will explain to you, how to read the character from the given file using fgetc in C programming with example. The fgetc function obtains that character as an unsigned char converted to an int.

Syntax of fgetc():

int fgetc(FILE *stream);

Where,

stream: Input stream (file pointer of an opened file)

 

Return value of fgetc in C:

On success, it returns the ASCII value of the character. On error or end of the file, it returns EOF.

 

Note: You have to include the stdio.h ( header file) before using fgetc in C Programming.

 

Example code to explain the working of fgetc function,

In the below code, I am reading a file using the fgetc. The file “aticleworld.txt” contains a string “I love File handling.”.

#include <stdio.h>
 
int main()
{
    //file pointer
    int ch = 0;
    FILE *fp = NULL;
 
    //open the file in read
    fp = fopen("aticleworld.txt", "r");
    if(fp == NULL)
    {
        printf("Error in creating the file\n");
        exit(1);
    }
 
    while( (ch=fgetc(fp)) != EOF )
    {
        //Display read character
        printf("%c", ch);
    }
 
    //close the file
    fclose(fp);
 
    printf("\n\n\nRead file successfully\n");
 
    return 0;
}

Output:

fgetc in c

 

 Code Analysis:

In the above c fgetc example, first, we opened the already created text (“aticleworld.txt”) file in reading mode and get the file pointer. Using the if condition I am verifying that the file has been opened successfully or not.

fp = fopen("aticleworld.txt", "r");
if(fp == NULL)
{
    printf("Error in creating the file\n");
    exit(1);
}

 

 

After opening the file successfully, I have used a while loop to traverse each and every character of the file (“aticleworld.txt”). The control comes out from the while loop when fgetc get the EOF.

while( (ch=fgetc(fp)) != EOF )
{
    //Display read character
    printf("%c", ch);
}

You can check this Article.

In the last, I have used fclose to close the open file.

//close the file
fclose(fp);

 

Difference between fgetc and getc in C.

The getc function is equivalent to fgetc but getc could be implemented as a macro. Because of the getc implemented as a macro so it may evaluate stream more than once.

Using of getc is risking because it is implemented a macro, so there might be a side effect occur due to the macro. It is good to use fgetc in place of getc.

Recommended Articles for you:

Reference: File input-output.



Leave a Reply

Your email address will not be published. Required fields are marked *