O_RDWR权限被拒绝

3

我创建了这个文件

char *output = "big";
creat(output, O_RDWR);

当我尝试读取文件时

 cat big

我得到了权限拒绝的错误。我的代码有什么问题?如何创建一个可读写文件的权限模式?

使用ls -l命令,big的权限看起来像这样:

----------

这是什么意思?
2个回答

4
您误解了模式参数。根据man页面的描述:
          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);

1
使用 0666 更为合适,因为它受到 umask 的影响。 - Neil

0

这显然是一个权限问题,开始尝试查看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”。


嗯,不对啊...你是用creat()还是open()创建的?open()函数中的"S_IRUSR | S_IWUSR"部分在文件创建时非常有用,它定义了文件的权限。正如man页面所述,"S_IRUSR -> 用户具有读取权限","S_IWUSR -> 用户具有写入权限","|"是逻辑门,使得S_IRUSR和S_IWUSR之间的结果为0600,因为00000100 | 00000010 = 00000110 = 6。所以0600中的6 :) - SeedmanJ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接