socay2 发表于 2012-10-27 19:10

creat 函数这个问题你知道吗?

在《Unix 环境高级编程》 一书中,说 access 总是以只写方式打开文件。 按照如下方式:
int fd;
fd = creat("txt", S_IRUSR); //各种容错判断就不写了
write(fd, "hello",5);
很明显创建的文件 txt 只具有读的权限。 问题来了
1、如果该 txt 文件不存在,则能够顺利的将字符串写到文件中去。(不是以读的方式创建的吗?怎么有写的权限了)
2、如果该文件已存在,且具备写的权限, 该文件将被截断,重新写如内容
3、如果该文件存在,且不具备写权限,那么 creat 将失败。

希望有大神着重解释下第一条。

dengxiayehu 发表于 2012-10-27 19:31

creat() is equivalent to open() with flags equal to O_CREAT|O_WRONLY|O_TRUNC.

socay2 发表于 2012-10-28 02:53

回复 2# dengxiayehu
恩,对。
但是问题在,我创建的文件根本就没给它写权限,为什么还能以写的方式打开呢?

   

linux_c_py_php 发表于 2012-10-28 10:24

NAME
       creat - create a new file or rewrite an existing one

SYNOPSIS
       #include <sys/stat.h>
       #include <fcntl.h>

       int creat(const char *path, mode_t mode);

DESCRIPTION
       The function call:

            creat(path, mode)

       shall be equivalent to:

            open(path, O_WRONLY|O_CREAT|O_TRUNC, mode)

socay2 发表于 2012-10-30 23:50

回复 4# linux_c_py_php


    那问题转到open
例如: open(filename, O_WRONLY|O_CREAT|O_TRUNC);
          第一次执行,成功,并且创建了一个只读文件
          重新执行一次,失败,不能用只写方式打开。
    问题就是,为什么在第一次创建文件的时候,该文件可以写?
页: [1]
查看完整版本: creat 函数这个问题你知道吗?