Read a file in C

To read a file in C, you can use standard library functions like fopen(), fgetc(), fgets(), or fread() depending on the type of data you want to read. Below, I’ll explain and provide examples of how to read a file in C using these functions.

Read a File in C

  1. Open the file using fopen().
  2. Read the file using one of the reading functions (fgetc(), fgets(), fread()).
  3. Close the file using fclose() when done.

fgetc() Method (Read Character by Character)

fgetc() reads a single character from a file. It returns the character read as an int (or EOF if the end of file is reached). It reads one character at a time from the file.

Example:


#include <stdio.h>

int main() {
    FILE *file = fopen("main.txt", "r");
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    char ch;
    // Read and print each character until EOF
    while ((ch = fgetc(file)) != EOF) {
        putchar(ch); // Print the character
    }

    fclose(file); // Close the file
    return 0;
}

fgets() Method (Read Line by Line)

fgets() reads a line of text from a file, including spaces, and stores it in a string (character array). It stops when either the maximum number of characters is reached or a newline (\n) is encountered. It reads an entire line (up to a specified size) from the file.

Example:


#include <stdio.h>

int main() {
    FILE *file = fopen("main.txt", "r");
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    char buffer[350];
    // Read and print each line
    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("%s", buffer);  // Print the line
    }

    fclose(file); // Close the file
    return 0;
}


fread() Method (Read Binary Data)

fread() is used to read binary data from a file into a buffer. It is useful for reading non-text files (e.g., images, audio, etc.) or large chunks of data at once.

Example:


#include <stdio.h>

int main() {
    FILE *file = fopen("main.txt", "r");
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }

    // Read the file in chunks (size of each chunk is 100 bytes)
    char buffer[350];
    size_t bytesRead;
    while ((bytesRead = fread(buffer, 1, sizeof(buffer), file)) > 0) {
        // Print the contents as characters (assuming text file)
        for (size_t i = 0; i < bytesRead; i++) {
            putchar(buffer[i]);
        }
    }

    fclose(file); // Close the file
    return 0;
}