How to Read a File in C

Jinku Hu Mar 12, 2025 C C File
  1. Using Standard I/O Functions
  2. Reading a File Line by Line
  3. Reading a File into an Array
  4. Conclusion
  5. FAQ
How to Read a File in C

Reading a file in C is an essential skill for any programmer looking to handle data efficiently. Whether you’re working on a small project or developing a large application, understanding how to read files can significantly enhance your program’s functionality.

In this article, we will explore various methods to read a file in C, providing you with clear examples and explanations. From using standard I/O functions to handling errors gracefully, we will cover everything you need to know to get started. So, let’s dive into the world of file handling in C and learn how to read files effectively.

Using Standard I/O Functions

One of the most common ways to read a file in C is by using the standard input/output library functions. The fopen, fgetc, and fclose functions are particularly useful for this purpose. Here’s a simple example that demonstrates how to read a file character by character.

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }
    
    char ch;
    while ((ch = fgetc(file)) != EOF) {
        putchar(ch);
    }
    
    fclose(file);
    return 0;
}

Output:

Hello, World!
This is a sample text file.

In this code, we first open a file named example.txt in read mode. If the file fails to open, we print an error message and exit the program. We then utilize a while loop to read each character from the file until we reach the end of the file (EOF). The putchar function prints each character to the console. Finally, we close the file to free up resources. This method is straightforward and effective for reading files in C.

Reading a File Line by Line

Another useful method for reading files in C is to read them line by line. This approach is particularly beneficial when dealing with text files that contain multiple lines of data. The fgets function can be used for this purpose. Here’s how you can implement it:

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }
    
    char buffer[256];
    while (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("%s", buffer);
    }
    
    fclose(file);
    return 0;
}

Output:

Hello, World!
This is a sample text file.

In this example, we again open the example.txt file for reading. We declare a buffer to hold each line of text. The fgets function reads a line from the file and stores it in the buffer until it encounters a newline character or the end of the file. We then print each line to the console. This method is particularly effective for processing structured data, as it allows you to handle each line individually.

Reading a File into an Array

If you need to store the contents of a file for further processing, reading the file into an array can be an effective strategy. This method allows you to access the data randomly rather than sequentially. Here’s how you can do it:

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }
    
    char **lines = malloc(100 * sizeof(char *));
    char buffer[256];
    int i = 0;
    
    while (fgets(buffer, sizeof(buffer), file) != NULL && i < 100) {
        lines[i] = malloc(strlen(buffer) + 1);
        strcpy(lines[i], buffer);
        i++;
    }
    
    for (int j = 0; j < i; j++) {
        printf("%s", lines[j]);
        free(lines[j]);
    }
    
    free(lines);
    fclose(file);
    return 0;
}

Output:

Hello, World!
This is a sample text file.

In this code, we first open the file and allocate memory for an array of strings to hold each line. We then read each line into a buffer and allocate memory for each line in the array. After reading the lines, we print them out and free the allocated memory to avoid memory leaks. This method is great for scenarios where you need to manipulate or analyze the data after reading it.

Conclusion

In summary, reading a file in C can be accomplished through various methods, each serving different needs. Whether you choose to read character by character, line by line, or store the data in an array, understanding these techniques will enhance your file handling capabilities. As you explore these methods, remember to handle errors gracefully and manage memory effectively. With practice, you will become proficient in reading files in C and using that data in your applications.

FAQ

  1. What libraries do I need to include to read files in C?
    You need to include the standard I/O library by adding #include <stdio.h> at the beginning of your program.

  2. How do I check if a file opened successfully in C?
    You can check if the file pointer returned by fopen is NULL. If it is, the file did not open successfully.

  3. Can I read binary files using the same methods?
    Yes, you can read binary files using similar functions, but you’ll need to use the binary mode when opening the file (e.g., "rb").

  4. What should I do if I reach the end of the file while reading?
    You can check for EOF (end-of-file) using the feof function or by checking if fgetc or fgets returns NULL.

  5. How can I handle memory allocation errors in C?
    Always check if the return value of malloc is NULL. If it is, handle the error appropriately, usually by freeing any previously allocated memory and exiting the program.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - C File