Check File Permissions before Accessing a File in C

To check file permissions before accessing a file in C, you can use functions like access() and stat() to verify whether a file has the required permissions (such as read, write, or execute) before performing any operations on it.


Example 1: Checking Read Permission using access()

In this example, we will use the access() function from unistd.h to check if the file test.txt has read permission before trying to open or process it.

main.c

</>
Copy
#include <stdio.h>
#include <unistd.h>

int main() {
    const char *filename = "test.txt";
    
    // Check if the file has read permission
    if (access(filename, R_OK) == 0) {
        printf("File has read permission\n");
    } else {
        printf("File does not have read permission\n");
    }
    return 0;
}

Explanation:

  1. The variable filename stores the name of the file (test.txt) to be checked.
  2. The access() function from unistd.h is used to check file permissions; here, R_OK tests for read permission.
  3. If access() returns 0, it means the file has the required read permission; otherwise, it does not.
  4. The program prints a corresponding message based on whether the file can be read.

Output:

File has read permission

Example 2: Checking File Permissions using stat()

In this example, we will use the stat() function from sys/stat.h to verify if the file test.txt exists and whether it has read permission for the owner.

main.c

</>
Copy
#include <stdio.h>
#include <sys/stat.h>

int main() {
    const char *filename = "test.txt";
    struct stat fileStat;

    // Retrieve file status
    if (stat(filename, &fileStat) < 0) {
        printf("File does not exist\n");
    } else {
        // Check if the file has read permission for the owner
        if (fileStat.st_mode & S_IRUSR) {
            printf("File has read permission for the owner\n");
        } else {
            printf("File does not have read permission for the owner\n");
        }
    }
    return 0;
}

Explanation:

  1. The variable filename holds the name of the file (test.txt) to be checked.
  2. A struct stat variable named fileStat is declared to store the file’s attributes.
  3. The stat() function retrieves the file status and fills the fileStat structure; if stat() returns a value less than 0, the file does not exist.
  4. The bitwise AND operation (&) with S_IRUSR checks if the file has read permission for the owner.
  5. The program prints an appropriate message based on the file’s permission status.

Output:

File has read permission for the owner

Conclusion

In this tutorial, we demonstrated two methods to check file permissions in C before accessing a file. The first method uses access() to directly check if a file can be read, while the second method uses stat() to retrieve detailed file attributes and verify the read permission for the owner.