open, creat - open and possibly create a file or device
打开一个文件,也可能创建一个文件,返回文件描述符
//头文件
#include
#include
#include
//接口
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
open有两套接口可供使用,下面介绍一下open的参数:
#include
#include
#include
#include int main()
{umask(0);int fd = open("log.txt", O_WRONLY | O_CREAT, 0666);printf("open success, fd: %d\n", fd);return 0;
}

执行程序之后,就在当前路径下创建了一个权限为rw-rw-rw的log.txt。
系统中也有默认的umask,如果程序中设置umask值就会使用程序中设置的(就近原则)。
关闭文件
//头文件
#include
//接口int close(int fd);
RETURN VALUE:close() returns zero on success. On error, -1 is returned, and errno is set appropriately.
write - write to a file descriptor
//头文件
#include
//接口ssize_t write(int fd, const void *buf, size_t count);
现在我们已经打开了一个文件,那么直接使用write向fd中写入:
const char* str = "hello write\n";
ssize_t s = write(fd, str, strlen(str));
log.txt:

write时要注意打开方式,打开时可以是O_APPEND,也可以是O_TRUNC。
现在log.txt已经写入了"hello write",那么我们看一下O_APPEND和O_TRUNC的不同点:
O_APPEND:

O_TRUNC:

open函数的第二个参数加上O_APPEND选项后,写入的数据会在文件的末尾追加;加上O_TRUNC之后打开文件会先清空文件,然后再向文件中写入。
写一段程序,清空文件中的数据。
#include
#include
#include
#include int main()
{int fd = open("log.txt", O_RDWR | O_TRUNC);close(fd);return 0;
}
read - read from a file descriptor
//头文件#include
//接口
ssize_t read(int fd, void *buf, size_t count);
使用read函数时open函数的第二个参数flags需要改变,O_WRONLY需要改为O_RDONLY或者O_RDWR;这样才能在文件中读取数据。

int main()
{umask(0);int fd = open("log.txt", O_RDWR | O_CREAT, 0666);// const char* str = "aa\n";// ssize_t s = write(fd, str, strlen(str));printf("open success, fd: %d\n", fd);char buffer[64];memset(buffer, '\0', sizeof(buffer));read(fd, buffer, sizeof(buffer));printf("%s\n", buffer);close(fd);return 0;
}
把文件中的数据读取到buffer中:

上一篇:一篇学习ES