C program to read the contents of a file character by character

C program to read the contents of a file character by character :

In this tutorial, we will learn how to read contents of file in C programming language. You can modify the program to read contents from multiple files if you want. The program will read the contents character by character and it will print out the reading character to the user.

C program :

#include <stdio.h>
#include <stdlib.h>

int main()
{
    //1
    FILE *filePointer;
    char ch;

    //2
    filePointer = fopen("example.txt", "r");

    //3
    if (filePointer == NULL)
    {
        printf("File is not available \n");
    }
    else
    {
        //4
        while ((ch = fgetc(filePointer)) != EOF)
        {
            printf("%c", ch);
        }
    }

    //5
    fclose(filePointer);

    return 0;
}

Explanation :

The commented numbers in the above program denote the step number below :

  1. Create one FILE pointer and one character variable. The pointer will point to the file we will open and the character variable will hold the current reading character.
  2. Open the file in read-mode. We are using ‘r’ for opening it on read mode. The file name is example.txt and it is in the same folder where the c file is saved.
  3. First of all, check if the filePointer is not NULL. If it is NULL, means the file doesn’t exist.
  4. Using one while loop, read the contents of the file one by one character.We are using fgetc method to read characters. Read it till the character is not end of file or EOF. Inside the loop, use one printf statement to print out the current reading character.
  5. Finally, close the file using fclose.

This function will print out the content saved in the example.txt file. c program read file

As you can see, the content of the .txt file I have saved on my drive contains only Hello World !! text.

Conclusion :

In this quick tutorial, we have learnt how to read the contents of a file character by character in C. Try to run the example program we have shown above and drop one comment below if you love this article and if you have any question.