具有被拒绝权限的open()函数

时间:2014-09-06 13:55:59

标签: c

我正在尝试在根目录中创建一个'test.txt'文件。目前我不是root用户。我的代码如下:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(){
    int fd;
    fd=open("/test.txt",O_CREAT|O_RDWR|O_TRUNC,0777);
    perror("error: ");
    close(fd);

    return 0;
}

但是,当我编译并执行它时,我收到错误:

error: : Permission denied

如何让我的代码拥有在根目录中创建文件的权限?

P.S。我正在努力使这个工作,以便我以后可以使用它将此方法应用于我的Linux守护程序。

1 个答案:

答案 0 :(得分:0)

    fd=open("/test.txt",O_CREAT|O_RDWR|O_TRUNC,0777);

在此行中正确指定路径。(即)当前工作目录是指.之前保持(点)/,如./test.txt

相关问题