我创建了这个文件
char *output = "big";
creat(output, O_RDWR);
当我尝试读取文件时
cat big
我得到了权限拒绝的错误。我的代码有什么问题?如何创建一个可读写文件的权限模式?
使用ls -l命令,big的权限看起来像这样:
----------
这是什么意思?
我创建了这个文件
char *output = "big";
creat(output, O_RDWR);
当我尝试读取文件时
cat big
我得到了权限拒绝的错误。我的代码有什么问题?如何创建一个可读写文件的权限模式?
使用ls -l命令,big的权限看起来像这样:
----------
mode specifies the permissions to use in case a new file is cre‐
ated. 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 only applies 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.
还有
creat() is equivalent to open() with flags equal to
O_CREAT|O_WRONLY|O_TRUNC.
int fd = creat(output, 0644); /*-rw-r--r-- */
如果你想以 O_RDWR
的方式打开它,那么只需使用 open()
:
int fd = open(output, O_CREAT|O_RDWR|O_TRUNC, 0644);
这显然是一个权限问题,开始尝试查看creat是否返回-1,如果是,则打印errno值,并使用perror("")解决问题。
在我看来,我宁愿使用open()来完成这个任务,因为如creat手册中所述, “请注意,open()可以打开设备特殊文件,但creat()无法创建它们;..”, “creat()等同于flags等于O_CREAT | O_WRONLY | O_TRUNC的open()”,而这并没有涉及到权限问题。
如果你这样做,结果将完全相同:
char* output = "big";
int fd;
fd = open(output, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
// do whaterver you want to do in your file
close(fd);
欲了解更多信息,请参考“man 2 open”。
0666
更为合适,因为它受到 umask 的影响。 - Neil