C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Read from a file

C Program: Read from a file

C

#include <stdio.h>

 

int main() {

    FILE *fp;

    char ch;

 

    // Step 1: Open file in read mode

    fp = fopen("output.txt", "r");

 

    // Step 2: Check if file exists

    if (fp == NULL) {

        printf("Error! File not found.\n");

        return 1;

    }

 

    // Step 3: Read file character by character

    printf("File contents:\n\n");

    while ((ch = fgetc(fp)) != EOF) {

        putchar(ch);

    }

 

    // Step 4: Close the file

    fclose(fp);

 

    return 0;

}

Output

 
Example Output :

If output.txt contains:

Hello, this is a file write example in C.


Program Output:
File contents:

Hello, this is a file write example in C.

Explanation

Step

Description

1

fopen("output.txt", "r") — Opens file for reading.

2

Checks if the file pointer is NULL (file may not exist).

3

Reads each character using fgetc() until EOF (end of file).

4

Displays each character using putchar().

5

Closes the file properly using fclose().