Linux——基础IO(1)
目录
0. 文件先前理解
1. C文件接口
1.1 写文件
1.2 读文件
1.3 输出信息到显示器
1.4 总结 and stdin & stdout & stderr
2. 系统调用文件I/O
2.1 系统接口使用示例
2.2 接口介绍
2.3 open函数返回值
3. 文件描述符fd及重定向
3.1 0 & 1 & 2
3.2 文件描述符fd的理解
3.3 文件描述符Linux内核源码分析
3.4 文件描述符的分配规则
3.5 重定向
3.6 使用 dup2 系统调用
4. 在minishell中添加重定向功能
5. 有关FILE缓冲区及Linux一切皆文件理解
5.1 一切皆文件及C语言实现运行时多态
5.2 缓冲区
5.3 C标准库FILE结构体及缓冲区
5.4 大致模拟缓冲区设计
0. 文件先前理解
文件 = 文件内容 + 文件属性
因此,对文件进行的操作无非:对内容,对属性
文件本质存放在磁盘上,访问文件,先写代码 -> 编译 -> exe -> 运行 ->访问文件,其本质是进程在访问文件!!!
要向硬件写入,只有操作系统具备权利,而普通用户写入,则需要使用操作系统提供的文件类系统调用接口,而语言层面对系统调用接口进行了封装,由于不同操作系统平台提供的系统调用接口不同,语言把所有平台的代码都实现条件编译—动态裁剪,使其语言具有跨平台性!如果语言不提供对文件的系统接口的封装,所有访问文件的操作,都必须使用OS的接口,一旦使用系统接口,编写所谓的文件代码,就无法在其他平台安全运行,就不再具有跨平台性。
学习OS层面的文件系统,本质是为了更好的理解不同语言底层操作实际是相通的!
显示器是硬件,而printf向显示器打印,本质也是一种写入!
Linux下,一切皆文件,又该如何理解?
文件而言:
曾经理解的文件,站在写程序的角度,将文件打开,加载到内存,进行read,write
显示器:printf,cout -> 一种write
键盘:scanf,cin -> 一种read
普通文件 -> fopen/fread -> 你的进程内部(内存) -> fwrite -> 文件中
input output
站在系统的角度,能够被input读取,或者output写出的设备就叫做文件!
狭义的文件——普通磁盘文件
广义上的文件——显示器,键盘,网卡,声卡,显卡,磁盘。几乎所有外色,都可以称之为文件
1. C文件接口
打开文件:fopen
打开方式: r,r+,w,w+,a,a+...
fopen以当前路径打开文件或者相对路径打开文件
当前路径默认是:当一个进程运行起来,在其pcb结构体中,没个进程都会记录当前所处的工作路径—cwd(创建工作的目录)即为该进程的当前路径!
1.1 写文件
//打开文件
FILE * fopen ( const char * filename, const char * mode );
//关闭文件
int fclose ( FILE * stream );
//fwrite:
size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );
buffer—要写入的数据 size—一个元素的大小 count—几个元素 stream—文件流
#include <stdio.h> #include <string.h> int main() {FILE* fp = fopen("myfile", "w");if (!fp) {printf("fopen error!\n");}const char* msg = "hello Linux!\n";int count = 5;while (count--) {fwrite(msg, strlen(msg), 1, fp);}fclose(fp);return 0; }
注意:这里写入字符串不计算'\0',因为字符串结束标志是C语言提供的,而不是操作系统所具有的!
1.2 读文件
//fread:
size_t fread( void *buffer, size_t size, size_t count, FILE *stream );
#include <stdio.h> #include <string.h> int main() {FILE* fp = fopen("myfile", "r");if (!fp) {printf("fopen error!\n");}char buf[1024];const char* msg = "hello Linux!\n";while (1) {size_t s = fread(buf, 1, strlen(msg), fp);if (s > 0) {buf[s] = 0;printf("%s", buf);}if (feof(fp)) {break;}}fclose(fp);return 0; }
1.3 输出信息到显示器
将写入的数据流入stdout,即输出到显示器
#include <stdio.h> #include <string.h> int main() {const char* msg = "hello fwrite\n";fwrite(msg, strlen(msg), 1, stdout);printf("hello printf\n");fprintf(stdout, "hello fprintf\n");return 0; }
1.4 总结 and stdin & stdout & stderr
C默认会打开三个输入输出流,分别是stdin, stdout, stderr
仔细观察发现,这三个流的类型都是FILE*, fopen返回值类型,文件指针
打开文件的方式:
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.
如上,是我们之前学的文件相关操作。还有 fseek ftell rewind 的函数,在C部分已经有所涉猎,请同学们自 行复习。
2. 系统调用文件I/O
操作文件,除了上述C接口(当然,C++也有接口,其他语言也有),我们还可以采用系统接口来进行文件访问, 先来直接以代码的形式,实现和上面一模一样的代码!
2.1 系统接口使用示例
open close read write O_CREAT O_TRUNC O_WRONLY O_RDONLY O_RDWR...
写文件:
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> int main() {umask(0);int fd = open("myfile", O_WRONLY | O_CREAT, 0644);if (fd < 0) {perror("open");return 1;}int count = 5;const char* msg = "hello Linux!\n";int len = strlen(msg);while (count--) {write(fd, msg, len);//fd: 后续, msg:缓冲区首地址, len: 本次读取,期望写入多少个字节的数//据。 返回值:实际写了多少字节数据}close(fd);return 0; }
读文件:
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> int main() {int fd = open("myfile", O_RDONLY);if (fd < 0) {perror("open");return 1;}const char* msg = "hello Linux!\n";char buf[1024];while (1) {ssize_t s = read(fd, buf, strlen(msg));//类比writeif (s > 0) {printf("%s", buf);}else {break;}}close(fd);return 0; }
在应用层看到一个很简单的动作,在系统接口层面甚至OS层面,可能要做非常多的动作!
2.2 接口介绍
open —— 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: 追加写 返回值:成功:新打开的文件描述符失败:-1
mode_t理解:直接 man 手册,比什么都清楚。
open 函数具体使用哪个,和具体应用场景相关,如目标文件不存在,需要open创建,则第三个参数表示创建文件的默认权限,否则,使用两个参数的open。
2.3 open函数返回值
在认识返回值之前,先来认识一下两个概念: 系统调用 和 库函数
- 上面的 fopen fclose fread fwrite 都是C标准库当中的函数,我们称之为库函数(libc)
- 而, open close read write lseek 都属于系统提供的接口,称之为系统调用接口
- 操作系统概念时,画的一张图
系统调用接口和库函数的关系,一目了然。 所以,可以认为,f#系列的函数,都是对系统调用的封装,方便二次开发。
3. 文件描述符fd及重定向
由上述系统调用open可知成功返回新打开的文件描述符(file descriptor)(fp)
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> int main() {//未做差错处理int fd1 = open("myfile1", o_rdonly);int fd2 = open("myfile2", o_rdonly);int fd3 = open("myfile3", o_rdonly);int fd4 = open("myfile4", o_rdonly);printf("open sucess, fd: %d", fd1);printf("open sucess, fd: %d", fd2);printf("open sucess, fd: %d", fd3);printf("open sucess, fd: %d", fd4);close(fd1);close(fd2);close(fd3);close(fd4);return 0; }
而打开多个文件,发现其fd从3开始依次递增!0,1,2去哪里了?
可知文件描述符就是一个小整数,如何理解文件描述符?
3.1 0 & 1 & 2
- Linux进程默认情况下会有3个缺省打开的文件描述符,分别是标准输入0, 标准输出1, 标准错误2.
- 0,1,2对应的物理设备一般是:键盘,显示器,显示器
- 所以输入输出还可以采用如下方式:
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> int main() {char buf[1024];ssize_t s = read(0, buf, sizeof(buf));if (s > 0) {buf[s] = 0;write(1, buf, strlen(buf));write(2, buf, strlen(buf));}return 0; }
3.2 文件描述符fd的理解
FILE* fopen(const char* path, const char* mode);
C标准库提供的文件操作可知,FILE是一个由C标准库提供的结构体
由上述可知,C语言库函数内部一定封装了系统调用接口,lib在系统调用之上,站在系统角度,操作系统并不认识C语言内部的FILE结构体,只认识fd,因此FILE结构体内部,必定封装了fd!!
所以,fd是什么?
进程想要访问文件,必须先打开文件
一般而言,进程 : 打开文件 = 1 :n
文件要被访问,前提是加载到内存中,才能直接被访问!
可知一个进程可以打开多个文件,多个进程运行时,会存在大量的被打开的文件,所以,操作系统需要把这些被各个进程打开的文件管理起来,如何管理?先描述,在组织!!!
而现在知道,文件描述符就是从0开始的小整数。当我们打开文件时,操作系统在内存中要创建相应的数据结构来描述目标文件。于是就有了file结构体。表示一个已经打开的文件对象。而进程执行open系统调用,所以必须让进 程和文件关联起来。每个进程都有一个指针*files, 指向一张表files_struct,该表最重要的部分就是包涵一个指针数组,每个元素都是一个指向打开文件的指针!所以,本质上,文件描述符就是该数组的下标。所以,只要拿着文件描述符,就可以找到对应的文件
3.3 文件描述符Linux内核源码分析
文件:磁盘文件(未被打开的文件) 内存文件(被进程打开的文件)
因此没每个进程的PCB中都一个文件表指针struct files_struct * files,指向一个struct files_struct文件表结构体,该文件表结构体内一定包含一个struct file* fd_array[]文件指针数组,其数组每个对应存取指向一个被打开文件结构体file的指针,file记录了该文件的所有属性及所有内容。
fwrite() -> FILE* -> fd -> write -> write(fd, ...) -> 自己执行操作系统内部的write方法 -> 能找到进程的task_struct -> *files -> files_struct -> fd_array[] -> fd_array[fd] -> struct file -> 内存文件被找到 -> 操作
#include<stdio.h> #include<stdlib.h>struct File {void(*read_p)();void(*write_p)(); };void readByKeyBoard() {cout << "从键盘读取" << endl; } void writeByKeyBoard() {cout << "nothing to do!" << endl; }void readByFile() {cout << "从文件读取" << endl; } void writeFile() {cout << "往文件写入" << endl; }void TestFile(struct File file) {file.read_p();file.write_p(); }int main() {struct File fileByKB;fileByKB.read_p = readByKeyBoard;fileByKB.write_p = writeByKeyBoard;struct File fileByFILE;fileByFILE.read_p = readByFile;fileByFILE.write_p = writeFile;TestFile(fileByFILE);TestFile(fileByKB);return 0; }
每个文件被加载到内存,其文件管理创建对应的file结构体,结构体内部会根据驱动填充相应的函数指针write,read等操作函数的地址,因为磁盘、显示器、键盘、网卡等不用硬件的读写方法不同,因此为了实现多态调用,C语言可以采用函数指针,实例化对象时填充不同的函数地址,以实现多态调用!
3.4 文件描述符的分配规则
直接看代码:
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main() {int fd = open("myfile", O_RDONLY);if(fd < 0){perror("open");return 1;}printf("fd: %d\n", fd);close(fd);return 0; }
输出发现是 fd: 3
关闭0或者2,在看
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main() {close(0);//close(2);int fd = open("myfile", O_RDONLY);if (fd < 0) {perror("open");return 1;}printf("fd: %d\n", fd);close(fd);return 0; }
发现是结果是: fd: 0 或者 fd 2 可见,文件描述符的分配规则:在files_struct数组当中,找到当前没有被使用的最小的一个下标,作为新的文件描述符。
3.5 重定向
那如果关闭1呢?看代码:
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> int main() {close(1);int fd = open("myfile", O_WRONLY | O_CREAT, 00644);if (fd < 0) {perror("open");return 1;}printf("fd: %d\n", fd);fflush(stdout);close(fd);exit(0); }
此时,发现,本来应该输出到显示器上的内容,输出到了文件 myfile 当中,其中,fd=1。这种现象叫做输出重定向。常见的重定向有:>, >>, <
重定向的本质,其实是在OS内部,更改fd对应的内容的指向!!!
3.6 使用 dup2 系统调用
函数原型如下:
#include<unistd.h>
int dup2(int oldfd, int newfd);
这里的oldfd copy 给 newfd,必要时会释放oldfd
代码如下:
#include <stdio.h> #include <unistd.h> #include <fcntl.h> int main() {int fd = open("./log", O_CREAT | O_RDWR);if (fd < 0) {perror("open");return 1;}close(1);dup2(fd, 1);for (;;) {char buf[1024] = { 0 };ssize_t read_size = read(0, buf, sizeof(buf) - 1);if (read_size < 0) {perror("read");break;}printf("%s", buf);fflush(stdout);}return 0; }
4. 在minishell中添加重定向功能
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<sys/wait.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<assert.h>#define NUM 1024 #define SIZE 32 char cmd_line[NUM];void dealStr(char* str, char** argv) {char* dealstr = NULL;const char* sep = " ";size_t i = 0;for (dealstr = strtok(str, sep); dealstr != NULL; dealstr = strtok(NULL, sep)) {if (i < SIZE) {argv[i] = dealstr;i++;}}if(strcmp(argv[0], "ls") == 0){argv[i] = (char*)"--color=auto";}argv[++i] = NULL; }#define INPUT_REDIR 1 #define OUTPUT_REDIR 2 #define APPEND_REDIR 3 #define NONE_REDIR 0 int redir_status = NONE_REDIR;char* CheckRedir(char* start){assert(start);//ls -a -l\0char* end = start + strlen(start) - 1;while(end >= start){if(*end == '>'){if(*(end - 1) == '>'){redir_status = APPEND_REDIR;*(end-1) = '\0';end++;break;}redir_status = OUTPUT_REDIR;*end = '\0';end++;break;//ls -a -l>myfile.txt//ls -a -l>>myfile.txt}else if(*end == '<'){redir_status = INPUT_REDIR;*end = '\0';end++;break;}else{end--;}}if(end >= start){return end;//要打开文件}else{return NULL;} }//环境变量保存的是地址,而拿不到环境变量本质是地址内容被清空,MY_VAL=NULL char buffer[64];//shell运行原理:通过让子进程执行命令,父进程等待&&解析命令 int main(){//extern char** environ;while(1){//1.打印提示信息printf("[root@localhost myshell]#");fflush(stdout);//2.获取用户输入memset(cmd_line, '\0', sizeof cmd_line);char *g_argv[SIZE] = { NULL };if(fgets(cmd_line, sizeof cmd_line, stdin) == NULL){continue;}cmd_line[strlen(cmd_line) - 1] = '\0';//printf("echo:%s\n", cmd_line);//"ls -a -l > log.txt" -> "ls -a -l\0log.txt"char* sep = CheckRedir(cmd_line);//3.命令行字符串分割dealStr(cmd_line, g_argv); //4.TODO 内置命令,让父进程(shell)自己执行的命令,叫做内置命令,内建命令// 内建命令本质就是shell中的一个函数调用if(strcmp("cd", g_argv[0]) == 0){//not child execute, father executeif(g_argv[1] != NULL)chdir(g_argv[1]);continue;}if(strcmp("export", g_argv[0]) == 0 && g_argv[1] != NULL){strcpy(buffer, g_argv[1]);putenv(buffer);//int checkPutenv = putenv(buffer);//if(checkPutenv == 0){// printf("Putenv sucess\n");// //for(size_t i = 0; environ[i]; i++){// //printf("%s\n", environ[i]);// // }//}else{// printf("Putenc fail\n");//}continue;}//5.forkpid_t id = fork();if(id < 0){perror("fork");exit(1);}else if(id == 0){if(sep != NULL){int fd = -1;switch(redir_status){case INPUT_REDIR:fd = open(sep, O_RDONLY);dup2(fd, 0);break;case OUTPUT_REDIR:fd = open(sep, O_WRONLY | O_TRUNC | O_CREAT, 0666);dup2(fd, 1);break;case APPEND_REDIR:fd = open(sep, O_WRONLY | O_APPEND);dup2(fd, 1);break;default:printf("bug?\n");break;}}//printf("getenv : %s\n", getenv("MY_VAL"));//execvpe(g_argv[0], g_argv, environ);//子进程继承父进程环境变量execvp(g_argv[0], g_argv);exit(1);}int status = 0;pid_t ret = waitpid(id, &status, 0);if(ret > 0){printf("exit code:%d -> result:%s\n",WEXITSTATUS(status), strerror(WEXITSTATUS(status)));}else{printf("wait fail!\n");exit(1);}}//end whilereturn 0; }
5. 有关FILE缓冲区及Linux一切皆文件理解
Linux设计则学——一切皆文件——体现在操作系统的软件设计层面的
5.1 一切皆文件及C语言实现运行时多态
Linux是C语言写的!如何用C语言实现面向对象,甚至是运行时多态?
可以使用结构体及函数指针实现面向对象!!!及运行时多态!!!
在Linux下,根据冯诺依曼体系结构,大部分硬件都输入IO设备,IO设备主要用于输入输出,因此根据其驱动层提供的读写方法,即可实现一切皆文件的概念!
所有的底层设备,都可以有自己的read和write方法的具体实现,但是,其具体的代码一定是不一样的!而通过函数指针使其根据硬件指向不同的读写方法,在调用时,就像在使用同一个函数!
5.2 缓冲区
1. 什么是缓冲区?
就是一段内存空间(这个空间社提供? 用户(char buffer[64], scanf(buffer))? 语言? OS?)
2. 为什么要有缓冲区
提高整机效率,主要是为了提高用户的响应速度!
写透模式(WT模式): 只要写就刷新,会进行频繁的IO操作,成本高,且效率慢!
回写模式(WB模式):提供缓冲区,定义刷新策略,IO操作次数降低,效率高!
缓冲区的刷新策略:
1. 立即刷新
2. 行刷新(行缓冲)
3. 满刷新(全缓冲)
特殊情况:
1. 用户强制刷新(fflush)
2. 进程退出
缓冲策略 = 一般 + 特殊, 缓冲策略是可控制的!
一般而言:行缓冲设备文件 —— 显示器 全缓冲设备文件 —— 磁盘文件
所有的设备,永远都倾向于全缓冲! —— 缓冲区满了,才刷新 --> 需要更少次的IO操作 --> 更少次的外设访问 --> 提高效率!
和外部设备进行IO的时候,数据量的大小不是主要矛盾,而和外设预备IO的过程是最耗费时间的!其他刷新策略是结合具体情况所做的妥协!
显示器:需要直接给用户看的,一方面照顾效率,一方面照顾用户体验,极端情况,是可以自定义规则的!
5.3 C标准库FILE结构体及缓冲区
因为IO相关函数与系统调用接口对应,并且库函数封装系统调用,所以本质上,访问文件都是通过fd访问的。 所以C库当中的FILE结构体内部,必定封装了fd。
来段代码在研究一下:
#include <stdio.h> #include <string.h> int main() {const char* msg0 = "hello printf\n";const char* msg1 = "hello fwrite\n";const char* msg2 = "hello write\n";printf("%s", msg0);fwrite(msg1, strlen(msg0), 1, stdout);write(1, msg2, strlen(msg2));fork();return 0; }
运行出结果:
hello printf hello fwrite hello write
但如果对进程实现输出重定向呢? ./hello > file , 我们发现结果变成了:
hello write hello printf hello fwrite hello printf hello fwrite
我们发现 printf 和 fwrite (库函数)都输出了2次,而 write 只输出了一次(系统调用)。为什么呢?肯定和 fork有关!
- 一般C库函数写入文件时是全缓冲的,而写入显示器是行缓冲。
- printf fwrite 库函数会自带缓冲区(进度条例子就可以说明),当发生重定向到普通文件时,数据 的缓冲方式由行缓冲变成了全缓冲。
- 而我们放在缓冲区中的数据,就不会被立即刷新,甚至fork之后
- 但是进程退出之后,会统一刷新,写入文件当中。
- 但是fork的时候,父子数据会发生写时拷贝,所以当你父进程准备刷新的时候,子进程也就有了同样的 一份数据,随即产生两份数据。
- write 没有变化,说明没有所谓的缓冲。
综上: printf fwrite 库函数会自带缓冲区,而 write 系统调用没有带缓冲区。另外,我们这里所说的缓冲区, 都是用户级缓冲区。其实为了提升整机性能,OS也会提供相关内核级缓冲区,不过不再我们讨论范围之内。 那这个缓冲区谁提供呢? printf fwrite 是库函数, write 是系统调用,库函数在系统调用的“上层”, 是对系统 调用的“封装”,但是 write 没有缓冲区,而 printf fwrite 有,足以说明,该缓冲区是二次加上的,又因为是 C,所以由C标准库提供。
如果有兴趣,可以看看FILE结构体:
在 / usr / include / libio.h struct _IO_FILE {int _flags; /* High-order word is _IO_MAGIC; rest is flags. */ #define _IO_file_flags _flags//缓冲区相关/* The following pointers correspond to the C++ streambuf protocol. *//* Note: Tk uses the _IO_read_ptr and _IO_read_end fields directly. */char* _IO_read_ptr; /* Current read pointer */char* _IO_read_end; /* End of get area. */char* _IO_read_base; /* Start of putback+get area. */char* _IO_write_base; /* Start of put area. */char* _IO_write_ptr; /* Current put pointer. */char* _IO_write_end; /* End of put area. */char* _IO_buf_base; /* Start of reserve area. */char* _IO_buf_end; /* End of reserve area. *//* The following fields are used to support backing up and undo. */char* _IO_save_base; /* Pointer to start of non-current get area. */char* _IO_backup_base; /* Pointer to first valid character of backup area */char* _IO_save_end; /* Pointer to end of non-current get area. */struct _IO_marker* _markers;struct _IO_FILE* _chain;int _fileno; //封装的文件描述符 #if 0int _blksize; #elseint _flags2; #endif_IO_off_t _old_offset; /* This used to be _offset but it's too small. */ #define __HAVE_COLUMN /* temporary *//* 1+column number of pbase(); 0 is unknown. */unsigned short _cur_column;signed char _vtable_offset;char _shortbuf[1];/* char* _save_gptr; char* _save_egptr; */_IO_lock_t* _lock; #ifdef _IO_USE_OLD_IO_FILE };
5.4 大致模拟缓冲区设计
#include<stdio.h> #include<string.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<assert.h> #include<stdlib.h>#define NUM 1024 typedef struct MyFILE_{int fd;char buffer[NUM];int end;//当前缓冲区结尾 }MFILE;MFILE* fopen_(const char* pathname, const char* mode){assert(pathname && mode);MFILE* fp = NULL;if(strcmp(mode, "r") == 0){}else if(strcmp(mode, "r+") == 0){}else if(strcmp(mode, "w") == 0){int fd = open(pathname, O_WRONLY | O_CREAT | O_TRUNC, 0666);if(fd >= 0){fp = (MFILE*)malloc(sizeof(MFILE));memset(fp, 0, sizeof(MFILE));fp->fd = fd;}}else if(strcmp(mode, "w+") == 0){}else if(strcmp(mode, "a") == 0){}else if(strcmp(mode, "a+") == 0){}else{}return fp; }void fputs_(const char* message, MFILE* fp){assert(message && fp);strcpy(fp->buffer + fp->end, message);fp->end += strlen(message);//for debugfprintf(stderr, "%s\n", fp->buffer);//暂时未刷新//制定刷新策略,刷新策略是由谁来执行的呢?//答案是用户通过执行C标准库中的代码逻辑,来完成刷新//效率提高体现,几行代码就减少频繁的IO操作执行次数(注:不是数据量)//stdinif(fp->fd == 0){//stdout}else if(fp->fd == 1){if(fp->buffer[fp->end-1] == '\n'){ // //for debug // fprintf(stderr, "fllush : %s", fp->buffer);write(fp->fd, fp->buffer, fp->end);fp->end = 0;}//stderr}else if(fp->fd == 2){}else{} }void fflush_(MFILE* fp){assert(fp);if(fp->end != 0){//暂且认为刷新了 -- 其实是把数据写到了内核中//如果想将数据由内核刷新到外设,系统调用sync-syncfswrite(fp->fd, fp->buffer, fp->end);syncfs(fp->fd);//将数据写入磁盘fp->end = 0;} }void fclose_(MFILE* fp){assert(fp);fflush_(fp);close(fp->fd);free(fp); } int main(){//close(1);MFILE* fp = fopen_("./log.txt", "w");if(fp == NULL){printf("open file error\n");return 1;}fputs_("one:hello world\n", fp);//fputs_("two:hello world\n", fp);//fputs_("three:hello world", fp);//fputs_("four:hello world\n", fp);//fputs_("five:hello world", fp);//行刷新策略 one one:two tree tree:four fivefork();//fork时,上下文数据写时拷贝,在缓冲区的one刷新两次fclose_(fp);return 0; }
相关文章:

Linux——基础IO(1)
目录 0. 文件先前理解 1. C文件接口 1.1 写文件 1.2 读文件 1.3 输出信息到显示器 1.4 总结 and stdin & stdout & stderr 2. 系统调用文件I/O 2.1 系统接口使用示例 2.2 接口介绍 2.3 open函数返回值 3. 文件描述符fd及重定向 3.1 0 & 1 & 2 3.2…...

MFC第二十七天 通过动态链表实现游戏角色动态增加、WM_ERASEBKGND背景刷新的原理、RegisterClass注册窗口与框架程序开发
文章目录 通过动态链表实现游戏角色动态增加CMemoryDC.hCFlashDlg.hCFlashDlg.cpp WM_ERASEBKGND背景刷新的原理RegisterClass注册窗口与框架程序开发CFrameRegister 通过动态链表实现游戏角色动态增加 CMemoryDC.h #pragma once#include "resource.h"/*内存DC类简介…...
Debezium系列之:基于内容路由实现把数据库表中的数据按照数据类型分发到不同的topic
Debezium系列之:基于内容路由实现把数据库表中的数据按照数据类型分发到不同的topic 一、需求背景二、创建表三、插入、更新、删除数据四、核心参数和实现技术五、查看分发的Topic六、消费Topic数据七、总结和延展一、需求背景 一张表中存有各个超市门店的订单信息,例如超市门…...
苹果账号被禁用怎么办?
苹果账号被禁用怎么办? 转载:苹果账号被禁用怎么办? 当我们使用苹果手机登录App Store时,有时会遇到账号被禁用的提示。总结下来, 账号被禁用的原因可能有以下几种: 禁用的原因 1.在不同的设备上登录Ap…...
文章一:快速上手Git - 从零到一:Git版本控制入门指南
开始本篇文章之前先推荐一个好用的学习工具,AIRIght,借助于AI助手工具,学习事半功倍。欢迎访问:http://airight.fun/。 概述 在软件开发和团队协作中,版本控制是一项至关重要的技术。Git作为现代开发者最喜爱的版本控…...

【用unity实现100个游戏之6】制作一个战旗自走棋类游戏(附源码)
文章目录 前言导入素材开始1. 设置瓦片间隙2. 放置全图瓦片3. 美化瓦片地图4. 添加树木障碍物5. 设定不同的排序图层6. 瓦片交互6. 瓦片交互优化6. 瓦片是否允许角色7. 添加角色8. 新增游戏管理脚本9. 角色移动范围逻辑10. 角色移动范围可视化11. 角色移动12. 重置瓦片颜色12. …...

W5100S-EVB-PICO 做TCP Server进行回环测试(六)
前言 上一章我们用W5100S-EVB-PICO开发板做TCP 客户端连接服务器进行数据回环测试,那么本章将用开发板做TCP服务器来进行数据回环测试。 TCP是什么?什么是TCP Server?能干什么? TCP (Transmission Control Protocol) 是一种面向连…...

dinput8.dll导致游戏打不开的解决方法,快速修复dinput8.dll文件
当你尝试启动某个游戏时,如果遇到dinput8.dll文件缺失或损坏的错误提示,可能会导致游戏无法正常运行。dinput8.dll是DirectInput API的一部分,它提供了游戏手柄、键盘和鼠标等输入设备的支持。本文将详细介绍dinput8.dll的作用、导致游戏无法…...
NAS相关
Debian11 更换软件源 备份 #备份软件源列表 cp /etc/apt/sources.list /etc/apt/sources.list.bak编辑sources.list nano /etc/apt/sources.list替换文件内容 deb http://mirrors.163.com/debian/ bullseye main non-free contrib deb http://mirrors.163.com/debian/ bull…...
26.Netty源码之ThreadLocal
highlight: arduino-light JDK ThreadLocal 如果你需要变量在多线程之间隔离,或者在同线程内的类和方法中共享,那么 ThreadLocal 大显身手的时候就到了。ThreadLocal 可以理解为线程本地变量,它是 Java 并发编程中非常重要的一个类。 ThreadL…...

Mysql SUBSTRING_INDEX - 按分隔符截取字符串
作用: 按分隔符截取字符串 语法: SUBSTRING_INDEX(str, delimiter, count) 属性: 参数说明str必需的。一个字符串。delimiter必需的。分隔符定义,是大小写敏感,且是多字节安全的count必须的。大于0或者小于0的数值…...

封装Ellipsis组件,亲测使用各种场景
自己封装了Ellipsis组件 基于reacttaro,以下是实现代码,分为JSX和CSS文件 JSX代码如下: import { FC, Fragment, JSX, useState } from react; import { Image, StandardProps, Text, View } from tarojs/components;import iconDropDown fr…...

Kendo UI for jQuery,一个现代的jQuery UI组件!
Kendo UI for jQuery是什么? Kendo UI for jQuery是完整的jQuery UI组件库,可快速构建出色的高性能响应式Web应用程序。Kendo UI for jQuery提供在短时间内构建现代Web应用程序所需要的工具,从多个UI组件中选择,并轻松地将它们组…...

C++初阶语法——类和对象
前言:C语言中的结构体,在C有着更高位替代者——类。而类的实例化叫做对象。 本篇文章不定期更新扩展后续内容。 目录 一.面向过程和面向对象初步认识二.类1.C中的结构体2.类的定义类的两种定义方式 3.类的访问限定符及封装访问限定符说明 4.类的实例化对…...

linux学习(进程创建)[8]
创建进程 myproc.c #include <stdio.h> #include <unistd.h>int main() {printf("我是父进程\n");pid_t id fork();if(id < 0){printf("创建子进程失败\n");return 1;}else if(id 0){while(1){printf("我是子进程: pid…...

Linux基础与应用开发系列九:各类系统函数
open_close函数 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 f…...

国产数据库排行
目录 一、理论 1.国产数据库排行 2.数据 一、理论 1.国产数据库排行 (1)墨天轮榜单 墨天轮国产数据库流行度排行于2019年6月推出,通过近50个维度的数据来考察近300个国产数据库的流行度排行,每月1日更新排行数据,…...
数学符号说明——三角等号(≜)
三角等号 ,LaTex语法宏 (\triangleq),Unicode(U225C),又称 "delta equal to(Δ 等)"。可以读作 "等于"、"根据定义 x 等于 y "。 有时候,用在数学(和物理学)的某种定义中。例如&#…...

健启星|医学营养的市场先行者
随着《“健康中国2030”规划纲要》、《国民营养计划(2017-2030年)》等政策的陆续发布,标志着以传统药物治疗为中心的医疗模式时代正式转型到以预防和康复为中心的新的医学营养时代。在此背景下,符合时代需求的特医食品成为“医学营…...

从 GPT4All 体验 LLM
推荐:使用 NSDT场景编辑器 助你快速搭建可编辑的3D应用场景 什么是 GPT4All? 术语“GPT”源自 Radford 等人 2018 年论文的标题“通过生成预训练提高语言理解”。本文描述了如何证明变压器模型能够理解人类语言。 从那时起,许多人尝试使用转…...

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式
一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明:假设每台服务器已…...

(十)学生端搭建
本次旨在将之前的已完成的部分功能进行拼装到学生端,同时完善学生端的构建。本次工作主要包括: 1.学生端整体界面布局 2.模拟考场与部分个人画像流程的串联 3.整体学生端逻辑 一、学生端 在主界面可以选择自己的用户角色 选择学生则进入学生登录界面…...
Oracle查询表空间大小
1 查询数据库中所有的表空间以及表空间所占空间的大小 SELECTtablespace_name,sum( bytes ) / 1024 / 1024 FROMdba_data_files GROUP BYtablespace_name; 2 Oracle查询表空间大小及每个表所占空间的大小 SELECTtablespace_name,file_id,file_name,round( bytes / ( 1024 …...

遍历 Map 类型集合的方法汇总
1 方法一 先用方法 keySet() 获取集合中的所有键。再通过 gey(key) 方法用对应键获取值 import java.util.HashMap; import java.util.Set;public class Test {public static void main(String[] args) {HashMap hashMap new HashMap();hashMap.put("语文",99);has…...
macOS多出来了:Google云端硬盘、YouTube、表格、幻灯片、Gmail、Google文档等应用
文章目录 问题现象问题原因解决办法 问题现象 macOS启动台(Launchpad)多出来了:Google云端硬盘、YouTube、表格、幻灯片、Gmail、Google文档等应用。 问题原因 很明显,都是Google家的办公全家桶。这些应用并不是通过独立安装的…...
基础测试工具使用经验
背景 vtune,perf, nsight system等基础测试工具,都是用过的,但是没有记录,都逐渐忘了。所以写这篇博客总结记录一下,只要以后发现新的用法,就记得来编辑补充一下 perf 比较基础的用法: 先改这…...

页面渲染流程与性能优化
页面渲染流程与性能优化详解(完整版) 一、现代浏览器渲染流程(详细说明) 1. 构建DOM树 浏览器接收到HTML文档后,会逐步解析并构建DOM(Document Object Model)树。具体过程如下: (…...
关于 WASM:1. WASM 基础原理
一、WASM 简介 1.1 WebAssembly 是什么? WebAssembly(WASM) 是一种能在现代浏览器中高效运行的二进制指令格式,它不是传统的编程语言,而是一种 低级字节码格式,可由高级语言(如 C、C、Rust&am…...
OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别
OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别 直接训练提示词嵌入向量的核心区别 您提到的代码: prompt_embedding = initial_embedding.clone().requires_grad_(True) optimizer = torch.optim.Adam([prompt_embedding...
uniapp中使用aixos 报错
问题: 在uniapp中使用aixos,运行后报如下错误: AxiosError: There is no suitable adapter to dispatch the request since : - adapter xhr is not supported by the environment - adapter http is not available in the build 解决方案&…...