Reading A Program or File


Explanation

In C, an existing file can be read using file handling functions. The fopen() function is used to open the file in "rt" (read text) mode. The fgetc() function reads one character at a time from the file and displays it using printf().

How It Works?

  • Step 1: Declare a file pointer using FILE *fp.
  • Step 2: Declare a character variable ch to store each character read from the file.
  • Step 3: Open the file using fopen("any.txt", "rt") in read mode.
  • Step 4: Use the feof() function to check whether the end of the file is reached.
  • Step 5: Read each character using fgetc().
  • Step 6: Display the file content using printf().
  • Step 7: Close the file after reading the data.

Example Program


#include <stdio.h>
#include <conio.h>

main()
{

    FILE *fp;
    char ch;

    clrscr();

    fp = fopen("any.txt", "rt");

    while(!feof(fp))
    {

        ch = fgetc(fp);

        printf("%c", ch);

    }

    fclose(fp);

    getch();

}

Output

Content of any.txt file will be displayed:

hello india
form of Program

Practice Exercises

Task 1: Write a C program to read the contents of a text file named student.txt and display all the data stored inside the file on the screen.

Goal: Learn how to open an existing file in read mode and display file contents using fgetc() and feof() functions.

💡 Hint: Open the file using fopen("student.txt","rt"). Use a while loop with feof() to read each character and display it using printf().
💡 Show Solution

#include <stdio.h>
#include <conio.h>

main()
{

    FILE *fp;
    char ch;

    clrscr();

    fp = fopen("student.txt", "rt");

    while(!feof(fp))
    {

        ch = fgetc(fp);

        printf("%c", ch);

    }

    fclose(fp);

    getch();

}

Output
Name : Rahul
Course : BCS
City : Pune
Explanation: The program opens the student.txt file in read mode using fopen(). The fgetc() function reads each character from the file one by one. The while loop continues until the end of the file is reached, and all file contents are displayed on the screen.