目录
模拟封装C库函数
下面我们来模拟实现如下fopen、fclose、fwrite、fflush这几个C库函数,代码如下:
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> #include<fcntl.h> #include<string.h> #include<assert.h> #include<stdlib.h> #define NUM 1024 #define NONE_FLUSH 0x0 //无缓冲 #define LINE_FLUSH 0x1 //行缓冲 #define FULL_FLUSH 0x2 //全缓冲 typedef struct _MyFILE { int _fileno; char _buffer[NUM]; int _end;//buffer缓冲区的结尾 int _flags;//标记fflush刷新策略 }MyFILE; //fopen MyFILE* my_fopen(const char* filename, const char* method) { assert(filename); assert(method); int flags = O_RDONLY; if (strcmp(method, "r") == 0) { } else if (strcmp(method, "r+") == 0) { } else if (strcmp(method, "w") == 0) { flags = O_WRONLY | O_CREAT | O_TRUNC;//写入方式 } else if (strcmp(method, "w+") == 0) { } else if (strcmp(method, "a") == 0) { flags = O_WRONLY | O_CREAT | O_APPEND;//追加方式 } else if (strcmp(method, "a+") == 0) { } int fileno = open(filename, flags, 0666); if (fileno < 0) { return NULL; } MyFILE* fp = (MyFILE*)malloc(sizeof(MyFILE)); if (fp == NULL) return fp; memset(fp, 0, sizeof(MyFILE)); fp->_fileno = fileno; fp->_flags |= LINE_FLUSH;//默认设置为行缓冲 fp->_end = 0; return fp; } //fflush void my_fflush(MyFILE* fp) { assert(fp); if (fp->_end > 0) { write(fp->_fileno, fp->_buffer, fp->_end); fp->_end = 0; syncfs(fp->_fileno);//把数据刷新到磁盘上 } } //fwrite void my_fwrite(MyFILE* fp, const char* start, int len) { assert(fp); assert(start); assert(len > 0); //abcde123 strncpy(fp->_buffer + fp->_end, start, len);//将数据写入到了缓冲区的结尾 fp->_end += len;//使end永远指向有效字符的下一个位置 if (fp->_flags & NONE_FLUSH) { } else if (fp->_flags & LINE_FLUSH) { if (fp->_end > 0 && fp->_buffer[fp->_end - 1] == '\n') { //仅仅是写入到内核中 write(fp->_fileno, fp->_buffer, fp->_end); fp->_end = 0; syn
模拟C库函数与添加重定向功能到自定义shell

文章展示了如何模拟实现C语言中的fopen、fclose、fwrite和fflush函数,并详细解释了每个函数的实现逻辑。接着讨论了如何在自定义的myshell中添加重定向功能,包括检查命令行中的重定向符号,设置重定向标志位和处理不同类型的重定向操作。最后给出了整体的代码示例和运行结果。
最低0.47元/天 解锁文章
3344

被折叠的 条评论
为什么被折叠?



