Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to read content from File

C Code Example — File Handling Programs

ADVERTISEMENT

C Program to read content from File

Objective

Write a C program to read and display the content of a File character by character.

Algorithm / Approach

  1. Create a FILE *fptr and a char ch variable.
  2. Open the file in Read mode: fptr = fopen("prowess.txt", "r").
  3. Check if the file exists (fptr != NULL).
  4. Use a do-while loop to read characters: ch = fgetc(fptr).
  5. Print each character.
  6. Stop the loop when ch equals EOF (End Of File).
main.c
#include<stdio.h>
int main( ) {
 FILE *fptr;
 char ch;
 fptr = fopen("prowess.txt","r");
 if(fptr != NULL) {
 do{
     ch = fgetc(fptr);
      printf("%c",ch);
  } while(ch!=EOF);

 return 0;
}

Expected Output

C is a Simple language

Explanation of the Program

  • The "r" mode tells C to open an existing file for reading. If the file doesn't exist, fopen() returns NULL.
  • The fgetc() function reads exactly one byte from the file and automatically advances the internal file cursor to the next byte. When it reaches the very end of the file, it returns a special hidden constant called EOF (-1).

Complexity

Time Complexity O(n) - Where n is the number of characters in the file.
Space Complexity O(1)
ADVERTISEMENT