0
0
CHow-ToBeginner · 3 min read

How to Open a File in C: Syntax and Example

In C, you open a file using the fopen function, which requires the file name and mode (like "r" for reading or "w" for writing). It returns a FILE* pointer that you use to access the file. Always check if fopen returns NULL to handle errors like missing files.
📐

Syntax

The basic syntax to open a file in C is:

FILE *fopen(const char *filename, const char *mode);

Here:

  • filename: The name of the file to open (string).
  • mode: How you want to open the file, for example:
    • "r" - read only
    • "w" - write only (creates or overwrites)
    • "a" - append (write at end)
  • The function returns a FILE* pointer if successful, or NULL if it fails.
c
FILE *file = fopen("example.txt", "r");
💻

Example

This example opens a file named example.txt for reading, checks if it opened successfully, reads one line, prints it, and then closes the file.

c
#include <stdio.h>

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

    char line[100];
    if (fgets(line, sizeof(line), file) != NULL) {
        printf("First line: %s", line);
    } else {
        printf("File is empty or error reading.\n");
    }

    fclose(file);
    return 0;
}
Output
First line: Hello, this is a sample line.
⚠️

Common Pitfalls

  • Not checking if fopen returns NULL can cause your program to crash when you try to use the file pointer.
  • Using the wrong mode (like "r" on a file that doesn't exist) will cause fopen to fail.
  • Forgetting to close the file with fclose can lead to resource leaks.
c
#include <stdio.h>

int main() {
    // Wrong: Not checking if file opened
    FILE *file = fopen("missing.txt", "r");
    // Using file without check can crash
    // fgets(..., file); // unsafe

    // Right way:
    if (file == NULL) {
        printf("Cannot open file.\n");
        return 1;
    }
    // Safe to use file now
    fclose(file);
    return 0;
}
Output
Cannot open file.
📊

Quick Reference

Here is a quick summary of common fopen modes:

ModeDescription
"r"Open for reading (file must exist)
"w"Open for writing (creates or overwrites)
"a"Open for appending (write at end)
"r+"Open for reading and writing (file must exist)
"w+"Open for reading and writing (creates or overwrites)
"a+"Open for reading and appending

Key Takeaways

Use fopen with the correct mode to open files in C.
Always check if fopen returns NULL to handle errors safely.
Close files with fclose to free resources.
Use modes like "r", "w", and "a" depending on your need to read, write, or append.
Reading or writing without checking file open status can cause crashes.