为什么O_CREAT只能创建管理员可以访问的文件?

时间:2013-09-20 20:30:52

标签: c++ linux

我有以下简单程序:

#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <string>

using namespace std;

int main() {
    string data { "The quick brown fox jumps over the lazy dog" };

    int file_descriptor = open("some_file.txt", O_CREAT | O_WRONLY);
    write(file_descriptor, data.c_str(), data.size());

    cout << file_descriptor << endl;
    return 0;
}

大部分工作正常 - 数据输出到文件中。但是根据http://linux.die.net/man/2/openO_CREAT标志应该将文件所有者设置为进程的有效用户ID。我正在从终端编译/运行我的应用程序,但没有任何类型的权限,那么为什么创建的文件只对管理员可见?

1 个答案:

答案 0 :(得分:10)

随机错误。当您使用O_CREAT时,open()是一个3参数函数,它将文件模式作为第三个参数。

您应该使用:

int fd = open("some_file.txt", O_CREATE | O_WRONLY, 0444);

这将创建一个没有任何人写入权限的文件(但您的进程可以写入该文件)。

有关用于代替0444的POSIX符号常量的更多信息,请参阅<sys/stat.h>

相关问题