0
0
CHow-ToBeginner · 3 min read

How to Read a File in C: Simple Syntax and Example

To read a file in C, use fopen to open the file, fgets or fread to read its contents, and fclose to close it. Always check if the file opened successfully before reading.
📐

Syntax

Here is the basic syntax to read a file line by line in C:

  • FILE *fp; declares a file pointer.
  • fp = fopen("filename", "r"); opens the file in read mode.
  • fgets(buffer, size, fp); reads a line from the file into a buffer.
  • fclose(fp); closes the file when done.
c
FILE *fp;
char buffer[100];

fp = fopen("filename.txt", "r");
if (fp == NULL) {
    // handle error
}

while (fgets(buffer, sizeof(buffer), fp) != NULL) {
    // process buffer
}

fclose(fp);
💻

Example

This example opens a file named example.txt, reads it line by line, and prints each line to the screen.

c
#include <stdio.h>

int main() {
    FILE *fp = fopen("example.txt", "r");
    if (fp == NULL) {
        printf("Failed to open file.\n");
        return 1;
    }

    char line[256];
    while (fgets(line, sizeof(line), fp)) {
        printf("%s", line);
    }

    fclose(fp);
    return 0;
}
Output
Hello, this is line 1. This is line 2. End of file.
⚠️

Common Pitfalls

Common mistakes when reading files in C include:

  • Not checking if fopen returns NULL, which means the file failed to open.
  • Using fgets without enough buffer size, causing incomplete reads.
  • Forgetting to close the file with fclose, which can cause resource leaks.
  • Using feof incorrectly to control loops, which can lead to reading the last line twice.
c
// Wrong way:
FILE *fp = fopen("file.txt", "r");
char line[10];
while (!feof(fp)) {
    fgets(line, sizeof(line), fp);
    printf("%s", line);
}
fclose(fp);

// Right way:
FILE *fp2 = fopen("file.txt", "r");
char line2[10];
while (fgets(line2, sizeof(line2), fp2) != NULL) {
    printf("%s", line2);
}
fclose(fp2);
📊

Quick Reference

Summary tips for reading files in C:

  • Use fopen with mode "r" to open files for reading.
  • Use fgets to read lines safely into a buffer.
  • Always check if fopen returns NULL before reading.
  • Close files with fclose to free resources.

Key Takeaways

Always check if the file opened successfully by verifying fopen does not return NULL.
Use fgets to read lines safely and avoid buffer overflow.
Close the file with fclose after finishing reading to release resources.
Avoid using feof to control reading loops; instead, check the return value of fgets.
Choose a buffer size large enough to hold the longest expected line.