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
- Create a
FILE *fptrand achar chvariable. - Open the file in Read mode:
fptr = fopen("prowess.txt", "r"). - Check if the file exists (
fptr != NULL). - Use a
do-whileloop to read characters:ch = fgetc(fptr). - Print each character.
- Stop the loop when
chequalsEOF(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 calledEOF(-1).
Complexity
Time Complexity
O(n) - Where n is the number of characters in the file.
Space Complexity
O(1)