0

I have a question about open() system call. I am writing a C code, in which I need to open all files from a provided directory in read only mode. Before the open call I check if the user has read permission to this file. Although when the provided directory is /, a file there swapfile cannot open and system call fails, while user has read permission.

Can someone tell me why this happens or how to correct it?

As you can see below user has read access, so the file should open.

-rw-------   1 root root 2147483648 Οκτ  22 18:58 swapfile

The code which is responsible for the error:

int fd = open(path, O_RDONLY);
if (fd == -1)
{
    perror("open");
    exit(1);
}        

The error:

open: Permission denied
10
  • 2
    What user are you running the code as?
    – Kusalananda
    Commented Jan 10, 2021 at 9:58
  • Sorry, what do you mean 'what user' ? I write the code in my personal pc.
    – user449420
    Commented Jan 10, 2021 at 10:01
  • 2
    The file is owned by root, are you running the code as the root user, or are you running the code as a non-privileged user?
    – Kusalananda
    Commented Jan 10, 2021 at 10:01
  • 1
    It has read permissions for the owner of the file, and the owner of the file is the root user according to your ls -l output.
    – Kusalananda
    Commented Jan 10, 2021 at 10:02
  • 1
    What you are doing (with your level of knowledge), in very very dangerous (for the computer OS). Commented Jan 10, 2021 at 11:34

1 Answer 1

3

You are trying to open the file as a non-root user.

The permissions on the file allows the owner of the file to open it for reading (and writing), and denies any sort of access to the group and to "others". This is what your ls -l output shows.

The owner of the file is the root user, and you are executing your code as user which is not root. This is why you get a "permission denied" error.

You must log in to answer this question.