函数的详细介绍可以用man命令来查看,例如 man 2 open.
#include
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
The open() system call opens the file specified by pathname. If the specified file does not exist, it may optionally (if O_CREAT is specified in flags) be created by open().
The return value of open() is a file descriptor, a small, nonnegative integer that is used in subsequent system calls (read(2), write(2), lseek(2), fcntl(2), etc.) to refer to the open file.The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process.
#include
#include
off_t lseek(int fd, off_t offset, int whence);
DESCRIPTION
lseek() repositions the file offset of the open file description associated with the file descriptor fd to the argument offset according to the directive whence as follows:
SEEK_SET
The file offset is set to offset bytes.
SEEK_CUR
The file offset is set to its current location plus offset bytes.
SEEK_END
The file offset is set to the size of the file plus offset bytes.
lseek() allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a “hole”) return null bytes (‘\0’) until data is actually written into the gap.
#include
ssize_t write(int fd, const void *buf, size_t count);
DESCRIPTION
write() writes up to count bytes from the buffer starting at buf to the file referred to by the file descriptor fd.
#include
ssize_t read(int fd, void *buf, size_t count);
DESCRIPTION
read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.
On files that support seeking, the read operation commences at the file offset, and the file offset is incremented by the number of bytes read. If the file offset is at or past the end of file, no bytes are read, and read() returns zero.
#include
#include
#include
#include
int main(){
int fd;
int write_data = 10;
int read_data;
fd = open("file",O_RDWR | O_CREAT,0644); //打开文件,若不存在就创建,权限:可读可写+可读+可读
lseek(fd,SEEK_SET,0); //设置写位置
write(fd,(char*)&write_data,sizeof(write_data)); //写入数据
lseek(fd,SEEK_SET,0); //设置读位置
read(fd,(char*)&read_data,sizeof(read_data)); //读取数据
printf("%d\r\n",read_data);
return 0;
}