Introduction

In C programming, working with files is an essential skill. Files are a way to store data persistently, and often we need to read data from files in our programs. This can be done using C’s standard library functions.

In this example, we will learn how to write a program that reads and displays the contents of a text file. The program will open a file in read mode, read its contents, and then display it on the screen.

Objective

The objective of this program is to demonstrate how to use basic file handling functions in C, such as fopen(), fgetc(), and fclose(), to read the contents of a file and print it to the console.

Program Code

#include 

int main() {
    FILE *file;
    char ch;

    // Open the file in read mode
    file = fopen("example.txt", "r");

    // Check if file opened successfully
    if (file == NULL) {
        printf("Error! Could not open file.\n");
        return 1; // Exit with error code
    }

    // Read and display the contents of the file
    printf("Contents of the file are:\n");
    while ((ch = fgetc(file)) != EOF) {
        putchar(ch);
    }

    // Close the file after reading
    fclose(file);

    return 0;
}

Explanation of the Program

This C program works as follows:

  • FILE *file; declares a pointer to a file structure.
  • fopen("example.txt", "r"); attempts to open the file named example.txt in read mode.
  • If the file is successfully opened, the program enters a loop where it reads one character at a time using fgetc() and prints it using putchar() until it reaches the end of the file (EOF).
  • Finally, the file is closed using fclose(file); to release system resources.

How to Run the Program

  1. Save the program in a file, say readfile.c.
  2. Ensure you have a file named example.txt in the same directory or update the file path in the program.
  3. Compile the program using a C compiler, e.g., using GCC: gcc readfile.c -o readfile.
  4. Run the program: ./readfile.
  5. The contents of the example.txt file will be displayed in the terminal.
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)