前言 大家好吖,欢迎来到 YY 滴Linux系列 ,热烈欢迎! 本章主要内容面向接触过C++的老铁 主要内容含:



如下图:进程结构体task_struct有一个文件指针指向files_struct结构体,files_struct结构体经过系统调用open后生成file结构体:



库函数有:库函数(libc):fopen,fclose,fread,fwrite等
FILE *fp = fopen("myfile", "w");//写
FILE *fp = fopen("myfile", "r");//读 r Open text file for reading.
The stream is positioned at the beginning of the file.
r+ Open for reading and writing.
The stream is positioned at the beginning of the file.
w Truncate(缩短) file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.
w+ Open for reading and writing.The file is created if it does not exist, otherwise it is truncated.
The stream is positioned at the beginning of the file.
a Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.
a+ Open for reading and appending (writing at end of file).The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.
查看手册:man 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);
pathname: 要打开或创建的目标文件
flags: 打开文件时,可以传入多个参数选项,用下面的一个或者多个常量进行“或”运算,构成flags。
参数:
O_RDONLY: 只读打开
O_WRONLY: 只写打开
O_RDWR : 读,写打开
这三个常量,必须指定一个且只能指定一个
O_CREAT : 若文件不存在,则创建它。需要使用mode选项,来指明新文件的访问权限
O_APPEND: 追加写
O_TRUNC: 先清空文件内容
返回值:
成功:新打开的文件描述符
失败:-1
mode_t:
权限设置//按照写方式的打开,文件不存在就创建,但会先清空文件内容
int fd = open("log.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
//按照写方式打开,文件不存在就创建,从文件结尾开始写入(追加,不先清空文件内容)
int fd = open("loga.txt", O_WRONLY | O_CREAT | O_APPEND, 0666);
close(fd);头文件:
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
参数:
fd:文件描述符,是一个非负整数,用于标识要写入数据的文件。
buf:写入数据的缓冲区的首地址
count:要写入的数据的字节数。
返回值:
成功时,返回实际写入的字节数。(这个值可能小于请求的字节数,但绝不会大于请求的字节数)
失败时,返回-1,并设置errno以指示错误类型。//打开文件,只写
int fd = open("example.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
//参数准备
int count = 5;
const char *msg = "hello bit!\n";
int len = strlen(msg);
//使用
while(count--){
write(fd, msg, len);
//fd: 文件描述符, msg:缓冲区首地址, len: 本次读取,期望写入多少个字节的数据。 返回值:实际写了多少字节数据
}头文件
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
参数:
fd:文件描述符,是一个非负整数,用于标识要读取数据的文件。
buf:指向用户空间中用于存储读取数据的缓冲区的指针。
count:要读取的数据的字节数。
返回值:
成功时,返回实际读取的字节数。这个值可能小于请求的字节数,表示已到达文件末尾或发生了其他读取限制。
失败时,返回-1,并设置errno以指示错误类型。//打开文件,只读
int fd = open("example.txt", O_RDONLY);
//参数准备
char buffer[1024];
ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1);
buffer[bytes_read] = '\0'; // 确保缓冲区以空字符结尾,用于字符串处理
close(fd);