C (programming language)

C program to read data from file using fgetc() function

Introduction

This guide will explore how to create a C program that effectively reads data from a file, character by character, using the fgetc() function. We’ll dive into the function’s purpose, code structure, and key steps involved in this process.

Understanding fgetc()

  • Purpose: fgetc() is a built-in C function designed to read a single character from a specified file stream.
  • Return Value: It returns the character read as an integer (EOF if the end of the file is reached or an error occurs).

Steps to Implement

  1. Include Necessary Header:

C

#include <stdio.h>
  1. Declare Variables:

C

FILE *fp;  // File pointer
char ch;   // Character to store the read character
  1. Open the File in Read Mode:

C

fp = fopen("filename.txt", "r");  // Replace "filename.txt" with the actual file name

if (fp == NULL) {
    printf("Error opening file!\n");
    return 1;
}
  1. Read Characters Using fgetc():

C

while ((ch = fgetc(fp)) != EOF) {
    printf("%c", ch);  // Print the character
}
  1. Close the File:

C

fclose(fp);

Complete Example Code:

C

#include <stdio.h>

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

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

    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    while ((ch = fgetc(fp)) != EOF) {
        printf("%c", ch);
    }

    fclose(fp);

    return 0;
}

Explanation

  1. fopen() opens the specified file in read mode and returns a file pointer.
  2. The while loop continues until fgetc() encounters the end of the file (EOF).
  3. Inside the loop, fgetc() reads a character from the file and assigns it to ch.
  4. printf() displays the character read from the file.
  5. fclose() closes the file to release resources.

Key Points to Remember

  • Always check for file opening errors using if (fp == NULL).
  • fgetc() reads characters one at a time, providing fine-grained control over file reading.
  • Close the file using fclose() when finished to avoid resource leaks.
  • For larger files or different reading patterns, consider functions like fgets() or fread().

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

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

Back to top button