#include <sys/types.h> int open(const char *pathname, int flags); int creat(const char *pathname, mode_t mode); |
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.
By default, the new file descriptor is set to remain open across an execve(2) (i.e., the FD_CLOEXEC file
descriptor flag described in fcntl(2) is initially disabled; the O_CLOEXEC flag, described below, can be
used to change this default). The file offset is set to the beginning of the file (see lseek(2)).
A call to open() creates a new open file description, an entry in the system-wide table of open files.
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.
pathname: 要打开的文件路径和名称
flags: 访问模式,宏定义和含义如下:
O_RDONLY 1 只读打开
O_WRONLY 2 只写打开
O_RDWR 4 读写打开
还可选择以下状态模式与以上3种基本模式相与:
O_CREAT 0x0100 创建一个文件并打开
O_TRUNC 0x0200 打开一个已存在的文件并将文件长度设置为0,其他属性保持
O_EXCL 0x0400 未使用
O_APPEND 0x0800 追加打开文件
O_TEXT 0x4000 打开文本文件翻译CR-LF控制字符
O_BINARY 0x8000 打开二进制字符,不作CR-LF翻译
mode: 该参数仅在flags=O_CREAT方式下使用,其取值如下:
S_IRWXU 00700 user (file owner) has read, write and execute permission
S_IRUSR 00400 user has read permission
S_IWUSR 00200 user has write permission
S_IXUSR 00100 user has execute permission
S_IRWXG 00070 group has read, write and execute permission
S_IRGRP 00040 group has read permission
S_IWGRP 00020 group has write permission
S_IXGRP 00010 group has execute permission
S_IRWXO 00007 others have read, write and execute permission
S_IROTH 00004 others have read permission
S_IWOTH 00002 others have write permission
S_IXOTH 00001 others have execute permission
#include <stdio.h> FILE *fopen(const char *path, const char *mode); FILE *fdopen(int fd, const char *mode); FILE *freopen(const char *path, const char *mode, FILE *stream); |
path: 文件名称
mode: 打开模式
r 只读方式打开一个文本文件
rb 只读方式打开一个二进制文件
w 只写方式打开一个文本文件
wb 只写方式打开一个二进制文件
a 追加方式打开一个文本文件
ab 追加方式打开一个二进制文件
r+ 可读可写方式打开一个文本文件
rb+ 可读可写方式打开一个二进制文件
w+ 可读可写方式创建一个文本文件
wb+ 可读可写方式生成一个二进制文件
a+ 可读可写追加方式打开一个文本文件
ab+ 可读可写方式追加一个二进制文件
open和fopen的区别:
前者属于低级IO,后者是高级IO。
前者返回一个文件描述符,后者返回一个文件指针。
前者无缓冲,后者有缓冲。
前者与 read, write 等配合使用, 后者与 fread, fwrite等配合使用。
后者是在前者的基础上扩充而来的,在大多数情况下,用后者。