1.open
int fd = open(const char *pathname,int flags,mode_t mode);
flags:
O_RDONLY 以只读方式打开 / O_WRONLY 以只写方式打开 /O_RDWR 以可读可写方式打开
O_CREAT 如果文件不存在则创建该文件
O_EXCL 如果使用O_CREAT选项且文件存在,则返回错误消息
O_NOCTTY 如果文件为终端,那么终端不可以调用open系统调用的那个进程的控制终端
O_TRUNC 如果文件已经存在泽删除文件中原有数据
O_APPEND 以追加的方式打开
2.close
int close(int fd);
3.read
size_t read(int fd, void *buf, size_t nbytes);
fd:文件描述符,标识要读取的文件。如果为0,则从标准输入读数据。
buf:缓冲区,用来存储读入的数据。
nbytes:要读取的字符数。
size_t:返回值,返回成功读取的字符数,它可能会小于请求的字节数。-1表示出现错误。
4.write
size_t write(int fd, const void *buf, size_t nbytes);
fd:文件描述符,目标文件。例如:fd的值为1,就向标准输出写数据,
buf:待写入的字符串。
nbytes:要写入的字符数。
size_t:函数返回值,返回成功写入文件的字符数。-1表示出现错误。
5.lseek(移动文件的读写位置)
off_t lseek(int fildes,off_t offset ,int whence);
参数 whence为下列其中一种:
SEEK_SET 参数offset即为新的读写位置。
SEEK_CUR 以目前的读写位置往后增加offset个位移量。
SEEK_END 将读写位置指向文件尾后再增加offset个位移量。
当whence 值为SEEK_CUR 或SEEK_END时,参数offet允许负值的出现。
下列是较特别的使用方式:
1) 欲将读写位置移到文件开头时:lseek(int fildes,0,SEEK_SET);
2) 欲将读写位置移到文件尾时:lseek(int fildes,0,SEEK_END);
3) 想要取得目前文件位置时:lseek(int fildes,0,SEEK_CUR);
返回值 当调用成功时则返回目前的读写位置,也就是距离文件开头多少个字节。若有错误则返回-1,errno 会存放错误代码。