Reading From External Files

Lesson 30
Author : Afrixi
Last Updated : January, 2023
C - Programming Language
This course covers the basics of programming in C.

Reading from external files in C involves opening the file, reading the contents, and then closing the file. Here’s an example of how to read from a text file in C:

#include <stdio.h>

int main() {
    FILE *filePointer;
    char fileName[] = "example.txt";
    char buffer[255];

    // Open the file for reading
    filePointer = fopen(fileName, "r");

    // Check if the file exists
    if (filePointer == NULL) {
        printf("File '%s' does not exist.\n", fileName);
        return 1;
    }

    // Read the contents of the file
    while (fgets(buffer, 255, filePointer)) {
        printf("%s", buffer);
    }

    // Close the file
    fclose(filePointer);

    return 0;
}

In this example, we declare a file pointer filePointer of type FILE, a character array fileName to hold the name of the file we want to read, and a character array buffer to hold the contents of each line of the file.

We then open the file using the fopen() function, with the "r" parameter to indicate that we want to read from the file. If the file does not exist, we print an error message and return from the program.

We then read the contents of the file line by line using the fgets() function, which reads a single line of text from the file and stores it in the buffer. We use a while loop to continue reading until we reach the end of the file.

Finally, we close the file using the fclose() function to free up any resources associated with the file.

Note that when reading from a file, it’s important to ensure that the file exists and that you have permission to read from it. Additionally, it’s important to check for errors when opening or reading from a file, as these operations can fail for a variety of reasons.