open
/close
打开文件 open and possibly create a file or device - open
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags)
int open(const char *pathname, int flags, mode_t mode)
DESCRIPTION:
- Given a
pathname
for a file,open()
returns a file descriptor, a small, nonnegative integer for use in subsequent system calls (read
(2),write
(2),lseek
(2),fcntl
(2), etc.). The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process. 打开或者创建一个文件
参数:
-
pathname
:要打开的文件名(含路径) -
The argument
flags
must include one of the following access modes:O_RDONLY
,O_WRONLY
, orO_RDWR
. These request opening the file read-only, write-only, or read/write, respectively. -
In addition, zero or more file creation flags and file status flags can be bitwise-or’d in
flags
. The file creationflags
areO_CLOEXEC
,O_CREAT
,O_DIRECTORY
,O_EXCL
,O_NOCTTY
,O_NOFOLLOW
,O_TRUNC
, andO_TTY_INIT
. -
O_RDONLY
:只读方式打开文件。O_WRONLY
:可写方式打开文件。O_RDWR
:读写方式打开文件。以上三个参数互斥
-
O_CREAT
: If the file does not exist it will be created. (如果该文件不存在,就创建一个新的文件,并用第三的参数为其设置权限。)mode
specifies the permissions to use in case a new file is created. This argument must be supplied whenO_CREAT
is specified inflags
; ifO_CREAT
is not specified, then mode is ignored. The effective permissions
are modified by the process’sumask
in the usual way: The permissions of the created file are (mode
&~umask
). Note that this mode applies only to future accesses of the newly created file; theopen()
call that creates a read-only file may well return a read/write file descriptor.- The following symbolic constants are provided for
mode
: (man 2 open)
-
O_EXCL
: Ensure that this call creates the file: if this flag is specified in conjunction withO_CREAT
, andpathname
already exists, thenopen()
will fail. (这一参数可测试文件是否存在) -
O_TRUNC
: If the file already exists and is a regular file and the open mode allows writing (i.e., isO_RDWR
orO_WRONLY
) it will be truncated to length 0. -
O_APPEND
: The file is opened in append mode. Before eachwrite
(2), the file offset is positioned at the
end of the file, as if withlseek
(2).O_APPEND
may lead to corrupted files on NFS filesystems if more than one process appends data to a file at once. This is because NFS does not support appending to a file, so the client kernel has to simulate it, which can’t be done without a race condition. -
mode
:一定是在flags
中使用了O_CREAT
标志,mode
记录待创建文件的访问权限。八进制数表示0666
所创建出的文件权限与umask
(文件权限掩码)(取反之后与)后得到最终的文件权限umask 0000
:将umask
值改为0000
返回值:open()
returns the new file descriptor, or -1
if an error occurred (in which case, errno
is set appropriately).
创建文件 creat
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
``int creat(const char *pathname, mode_t mode)`
DESCRIPTION: 创建一个文件,并以只写的方式打开该文件
参数:
pathname
:创建的文件名(含路径)mode
:创建的文件的读写权限
返回值:
- 成功:文件描述符
- 失败:
-1
...
fd = creat("/home/linux/文档/test2.c", 0621)