Linux系统编程13 系统调用IO - open,close

open / close


man 2 open
NAME
open, openat, creat - open and possibly create a file

SYNOPSIS
#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);
   int creat(const char *pathname, mode_t mode);

RETURN VALUE
open() and creat() return the new file descriptor, or -1 if an error occurred (in which case, errno is set appropriately).
返回文件描述符或者-1,失败就是返回-1,因为数组下标没有复数(复习前一节 文件描述符的本质)

参数
flags
The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read-only, write-only, or read/write, respectively.
必须包含:O_RDONLY, O_WRONLY, O_RDWR 其中一个,分别是只读,只写,读写。

In addition, zero or more file creation flags and file status flags can be bitwise-or’d in flags. The file creation flags are O_CLOEXEC, O_CREAT, O_DIRECTORY, O_EXCL, O_NOCTTY, O_NOFOLLOW, O_TMPFILE, and O_TRUNC. The file status flags are all of the remaining flags listed below. The distinction between these two groups of flags is that the file status flags can be retrieved and (in some cases) modified; see fcntl(2) for details.

另外,要包含零个或多个 文件的创建选项文件的状态选项,以按位或的形式放到flags 中。

文件创建选项包含:

O_CLOEXEC

O_CREAT :无则创建

O_DIRECTORY:
如果path 引用的不是目录,则出错。

O_EXCL:
必须打开一个新文件,如果指定了该文件创建为,并且打开的文件已经存在,则报错,该文件创建标志选项可以用来测试一个文件是否存在。

O_NOCTTY

O_NOFOLLOW:
如果文件名是符号链接文件的话,则打开失败。
O_TMPFILE

O_TRUNC:
如果文件存在,并且为只写或读写 方式成功打开,则将其长度截断为0

文件的状态选项包含:

O_APPEND
每次写的时候都追加到文件尾端

O_ASYNC
O_DIRECT
O_DSYNC

O_LARGEFILE:
如果打开的文件比较大,可以指定O_LARGEFILE

O_NOATIME:
ATIME是指文件最后读的时间,O_NOATIME 是指不修改文件最后读的时间

O_NONBLOCK or O_NDELAY:
非阻塞,非等待

O_PATH
O_SYNC

标准IO 与 文件IO 映射

r -> O_RDONLY
r+ -> O_RDWR
w -> O_WRONLY | O_CREAT | O_TRUNC , 只写 有则清空,无则创建
w+ -> O_RDWR | O_TRUNC | O_CREAT, 读写,有则清空,无则创建

cache VS buffer

buffer:可以理解为 写的缓冲区,写是先写到buffer中去,即buffe 是写的加速机制
cache:可以理解为 读的缓冲区,读内容是先读到 cache里面来,即cache 是读的加速机制

open(2参数) VS open(3参数)

   int open(const char *pathname, int flags);
   VS
   int open(const char *pathname, int flags, mode_t mode);

如果 flags 中有 O_CREAT ,那么要用三参的open, 如果 flag中没有O_CREAT 那么就要用两参的形式。mode 指的是创建新文件的权限。
依然是 mode & ~umask


NAME
close - close a file descriptor

SYNOPSIS
#include <unistd.h>

   int close(int fd);

猜你喜欢

转载自blog.csdn.net/LinuxArmbiggod/article/details/105850767