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?
FILE *fp.ch to store each character read from the file.fopen("any.txt", "rt") in read mode.feof() function to check whether the end of the file is reached.fgetc().printf().#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(); }
Content of any.txt file will be displayed:
fgetc() and feof() functions.fopen("student.txt","rt"). Use a while loop with feof() to read each character and display it using printf().
#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(); }
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.