C Program to Read and Print the Content of a File
Subject: PPS (Programming for Problem Solving)
Contributed By: Sanjay
Created At: February 3, 2025
Question:
Write a C Program to Read and Print the Content of a File
Explanation Video:
Explanation:
- We use fopen() to open the file in read mode.
- We use fgets() to read content line by line.
- fclose() is used to close the file.
Source Code:
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("example.txt", "r"); // Open file in read mode
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
while ((ch = fgetc(fp)) != EOF) { // Read character by character
putchar(ch); // Print each character
}
fclose(fp); // Close the file
return 0;
}
Input:
Input (Content of example.txt):
Hello, this is a test file!
Output:
Hello, this is a test file!