3

我创建了这个文件

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

当我试图读取文件时

 cat big

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

用ls -l,大的权限是这样的

----------

这是什么意思?

4

2 回答 2

4

您误解了模式参数。从手册页:

          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);
于 2013-02-21T22:17:38.783 回答
0

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

恕我直言,我宁愿使用 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”

于 2013-02-21T22:15:56.843 回答