c - open() 函数参数

标签 c posix

如果您在考虑最后一个参数“0”的情况下查看下面的代码块,写行是否正常工作?

filename = argv[1];
string = "Example string";
if (stat(argv[1], &buf) != 0)
{
    fd = open(filename, O_WRONLY | O_CREAT, 0);
    if (fd < 0)
    {
        perror(filename);
        exit(1);
    }
    write(fd, string, strlen(string));
    close(fd);
}
else
{
    print("%s file exists\n", filename);
}

最佳答案

来自手册页:

mode specifies the permissions to use in case a new file is created. This argument must be supplied when O_CREAT is specified in flags; if O_CREAT is not specified, then mode is ignored. The effective permissions are modified by the process's umask in the usual way: The permissions of the created file are (mode & ~umask). Note that this mode applies only to future accesses of the newly created file; the open() call that creates a read-only file may well return a read/write file descriptor.

The following symbolic constants are provided for mode:

S_IRWXU  00700 user (file owner) has read, write and execute permission
S_IRUSR  00400 user has read permission
S_IWUSR  00200 user has write permission
S_IXUSR  00100 user has execute permission
S_IRWXG  00070 group has read, write and execute permission
S_IRGRP  00040 group has read permission
S_IWGRP  00020 group has write permission
S_IXGRP  00010 group has execute permission
S_IRWXO  00007 others have read, write and execute permission
S_IROTH  00004 others have read permission
S_IWOTH  00002 others have write permission
S_IXOTH  00001 others have execute permission

因此,将 mode 指定为零,您将创建一个具有 0 & ~umask 权限的文件,即文件 < strong>没有任何权限。

文件系统究竟做了什么不在 open()write() 函数的范围内。

关于c - open() 函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37543659/

相关文章:

c++ - Cuda "invalid argument"二维数组 - 元胞自动机

objective-c - 通过指针运算与 C 中的下标访问数组值

c++ - Scilab 编译 "cannot allocate this quantity of memory"

c++ - CUDA C - 无法编译在头文件中声明并在 .cu 中实现的类

c++ - 在信号处理函数中使用本地互斥量来同步共享数据

c - mq_open 给出 "too many open files"

c - SCHED_IDLE 是否实际上排除了在非空闲内核上的执行?

c - 将文件详细信息读入字符串和 int

c - 为什么在进程退出时数据没有被刷新到文件?

c - 应用程序退出后信号量保持打开状态