O_RDWR权限被拒绝

时间:2013-02-21 22:03:48

标签: c unix permissions

我创建了这个文件

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

当我尝试阅读文件时

 cat big

我被拒绝了。我的代码有什么问题?如何使用读写权限模式创建文件?

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

----------
这是什么意思?

2 个答案:

答案 0 :(得分:2)

你错误地混淆了mode参数。从手册页:

          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 :(得分:0)

这显然是一个权限问题,开始尝试查看creat是否返回-1,如果是,则打印errno值,使用perror(“”),以便您可以解决问题。

Imho,我宁愿使用open()来做这件事,因为正如在creat手册页中提到的那样, “请注意,open()可以打开设备专用文件,但creat()无法创建它们; ..”和 “creat()等同于open(),其中的标志等于O_CREAT | O_WRONLY | O_TRUNC”,这里没有谈到权限..

如果你这样做,那将是完全相同的结果:

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”