1: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);
(若存在新创建则需加上其文件的权限,eg:0664(r:4,w:2,x:1))
flags有
O_RDONLY 以只读方式打开文件
O_WRONLY 以只写方式打开文件
O_RDWR 以可读写方式打开文件。上述三种旗标是互斥的,也就是不可同时使用,但可与下列的旗标利用OR(|)运算符组合。
O_CREAT 若欲打开的文件不存在则自动建立该文件。
O_APPEND 追加文件内容
O_TRUNC 清空文件
RETURN VALUE
open() and creat() return the new file descriptor, or -1 if an error occurred (in which case, errno is set appropriately).
(翻译:open()和creat()返回新的文件描述符,如果出现错误,则返回-1(在这种情况下,errno被适当地设置))即说明open的返回值为一个新的文件描述符(fd),(即每一个都有可能返回),但是若打开失败则返回的是-1。
2:read函数:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
RETURN VALUE
On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not anerror if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because weare reading from a pipe, or from a terminal), or because read() was interrupted by a signal. On error, -1 is returned, and errno is setappropriately. In this case it is left unspecified whether the file position (if any) changes.
(翻译:在成功的时候,读取的字节数被返回(0表示文件的结束),并且文件位置被这个数字所增加。如果这个数字小于请求的字节数,那就不是一个错误;例如,这可能会发生,因为现在实际可用的字节更少(可能是因为我们接近文件结束,或者因为我们从管道中读取,或者从终端读取),或者因为read()被一个信号中断了。在错误中,返回-1,并适当地设置errno。在本例中,没有指明文件位置(如果有的话)是否发生了变化。)
即调用read时,若所要读取的字节数少于文件中的个数,则返回读取到的字节个数;若要读取的个数多于文件中的个数,这不算错误,也返回的是读取到的字节数;若文件为空了,所返回的值即为0;若读取失败,则返回-1。
这里说的文件位置被这个数字增加的意思是你读取一位,指向字节的文件的光标往后移动一位。
3:write函数
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
RETURN VALUE
On success, the number of bytes written is returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately.
(翻译:在成功时,返回的字节数(零表示没有写入)。在错误中,返回-1,并适当地设置errno。)
写入文件的时候光标也会往后移动。
4:lseek函数
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
(offset即size,whence即从那个位置开始偏移
1: SEEK_SET (起始位)
2: SEEK_CUR(当前位置)
3: SEEK_END (末尾) )
RETURN VALUE
Upon successful completion, lseek() returns the resulting offset loca-tion as measured in bytes from the beginning of the file. Otherwise, a value of (off_t) -1 is returned and errno is set to indicate the error.
(翻译:在成功完成后,lseek()将从文件开始时以字节数的方式返回结果的偏移位置。否则,返回的值为(off_t) -1, errno将被设置为表示错误。)
当调用成功时则返回目前的读写位置,也就是距离文件开头多少个字节。若有错误则返回-1,errno 会存放错误代码。
5:close函数
#include <unistd.h>
int close(int fd);
RETURN VALUE
close() returns zero on success. On error, -1 is returned, and errno is set appropriately.
close()在成功时返回零。在错误中,返回-1,并适当地设置errno。