打开使用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);
是不正确的。所有标志都在第二个参数中,与按位或组合在一起,第三个参数用于“模式”,即访问权限。当然,请参阅手册页了解更多详细信息。
所以,应该是:
const int fd2 = open("output.txt", O_CREAT | O_TRUNC | O_WRONLY, S_IRWXU);
这将以模式打开S_IRWXU,即仅授予所有者读/写/执行权限。