Course contentsShow
← C
Lesson 745 of 1,21910. Input and OutputFree lesson

Handling 'Permission Denied' errors

Handling 'Permission Denied' errors

What you'll learn: How to identify and respond when your program is blocked from accessing a file by the operating system.

The "Locked Room" Problem

Imagine you have a key to a building, but when you try to turn the lock on a specific office door, it won't budge. You have the right tool (the key), but you lack the "clearance" to enter. In C, this is exactly what happens when you encounter a Permission Denied error.

Even if a file exists, your program might fail to open it because the file is marked "read-only," owned by another user, or located in a protected system folder. If you don't check for this, your program will crash or behave unpredictably when it tries to read data that isn't there.

Checking the errno

When the fopen() function fails, it returns NULL. However, NULL only tells you that something went wrong, not why. To find the specific cause, C uses a global variable called errno. When a permission issue occurs, the system sets errno to a specific code: EACCES.

Practical Implementation

To handle this, you need to include <errno.h>. You can then use perror(), a handy function that prints a human-readable description of the last error that occurred.

#include <stdio.h>
#include <errno.h>

int main() {
    // Attempting to open a system file for writing (usually restricted)
    FILE *file = fopen("/root/secret.txt", "w");

    if (file == NULL) {
        if (errno == EACCES) {
            printf("Error: You do not have permission to write to this file.\n");
        } else {
            perror("An unexpected error occurred");
        }
        return 1;
    }

    fclose(file);
    return 0;
}

Why this matters

Good software is resilient. By specifically checking for EACCES, you can give your users helpful feedback—like "Please run this as an Administrator"—rather than leaving them staring at a generic "File not found" message or a sudden crash. It turns a frustrating failure into a clear instruction.

Key takeaway

Use errno and the EACCES constant to detect permission issues, and always provide clear feedback to the user when access is denied.