打开使用 C 编写的文件时权限被拒绝

Permission denied when opening a file written using C

我正在使用以下代码对文件描述符进行一些简单的练习:

int main(int argc, char *argv[]){
    int fd1 = open("etc/passwd", O_RDONLY);
    int fd2 = open("output.txt", O_CREAT,O_TRUNC,O_WRONLY);

    dup2(fd1,0);
    close(fd1);

    dup2(fd2,1);
    close(fd2);
}

每当我尝试打开“output.txt”时,我都会收到以下错误:

Unable to open 'output.txt': Unable to read file '/home/joao/Desktop/Exercicios/output.txt' (NoPermissions (FileSystemError): Error: EACCES: permission denied, open '/home/joao/Desktop/Exercicios/output.txt').

尽管我认为某些错误与 VSCode 有关,但我无法在任何地方打开该文件。这是我在包含 .c 文件、可执行文件和“output.txt”的文件夹上执行“ls -l”时得到的结果:

---------T 1 joao joao     0 jun  9 21:54 output.txt
-rwxrwxr-x 1 joao joao 16784 jun  9 21:54 test
-rw-rw-r-- 1  700 joao   387 jun  9 21:54 teste.c

我该如何解决这个问题?

这个:

int fd2 = open("output.txt", O_CREAT,O_TRUNC,O_WRONLY);

不对。 All 标志位于第二个参数中,与按位或组合,第三个用于“模式”,即访问权限。当然,请参阅 the manual page 了解更多详细信息。

所以,应该是:

const int fd2 = open("output.txt", O_CREAT | O_TRUNC | O_WRONLY, S_IRWXU);

这将以 S_IRWXU 模式打开,即只为所有者授予 read/write/execute 权限。