当前位置: 首页 > news >正文

Linux:libc库简单设计

简单设计MyFopen,MyFclose,MyFwrite,MyFFlush

mystdio.h

#pragma once
#include<stdio.h>#define MAX 1024
#define NONE_FLUSH 1<<0
#define LINE_FLUSH 1<<1
#define FULL_FLUSH 1<<2typedef struct IO_FILE
{int fileno;int flag;char outbuffer[MAX];int bufferlen;int flush_method;
}MyFile;MyFile* MyFopen(const char* path, const char* mode);
void MyFclose(MyFile*);
int MyFwrite(MyFile*, void* str, int len);
void MyFFlush(MyFile*);

mystdio.c

#include"mystdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>static MyFile* BuyFile(int fd, int flag)
{MyFile* f = (MyFile*)malloc(sizeof(MyFile));if (f == NULL) return NULL;f->fileno = fd;f->flag = flag;f->bufferlen = 0;f->flush_method = LINE_FLUSH;memset(f->outbuffer, 0, sizeof(f->outbuffer));return f;
};MyFile* MyFopen(const char* path, const char* mode)
{int fd = -1;int flag = 0;if (strcmp(mode, "w") == 0){flag = O_CREAT | O_WRONLY | O_TRUNC;fd = open(path, flag, 0666);}else if (strcmp(mode, "a") == 0){flag = O_CREAT | O_WRONLY | O_APPEND;fd = open(path, flag, 0666);}else if (strcmp(mode, "r") == 0){flag = O_RDWR;fd = open(path, flag);}else{}if (fd < 0)return NULL;return BuyFile(fd, flag);
}void MyFclose(MyFile* file)
{if (file->fileno < 0) return;MyFFlush(file);close(file->fileno);free(file);
}int MyFwrite(MyFile* file, void* str, int len)
{memcpy(file->outbuffer + file->bufferlen, str, len);file->bufferlen += len;if (file->flush_method & LINE_FLUSH && file->outbuffer[file->bufferlen - 1] == '\n'){MyFFlush(file);}return 0;
}void MyFFlush(MyFile* file)
{if (file->bufferlen <= 0) return;int n = write(file->fileno, file->outbuffer, file->bufferlen);(void)n;fsync(file->fileno);file->bufferlen = 0;
}

usercode.c

#include "mystdio.h"
#include <string.h>
#include <unistd.h>int main()
{MyFile* filep = MyFopen("./log.txt", "a");if (!filep){printf("fopen error!\n");return 1;}int cnt = 10;while (cnt--){char* msg = (char*)"hello myfile!!!";MyFwrite(filep, msg, strlen(msg));MyFFlush(filep);printf("buffer: %s\n", filep->outbuffer);sleep(1);}MyFclose(filep); // FILE *fpreturn 0;
}

相关文章:

  • RAG技术在测试用例生成中的应用
  • Android RecyclerView自带的OnFlingListener,Kotlin
  • 力扣-142.环形链表II
  • Windows (可永久)暂停更新用以解决兼容性、性能与稳定性问题
  • pytest自动化测试框架搭建,并生成allure测试报告
  • 基础编程题目集 6-9 统计个位数字
  • 二元随机响应(Binary Randomized Response, RR)的翻转概率
  • 手撕基于AMQP协议的简易消息队列-4(项目需求分析)
  • 如何查看某个文件中的特殊符号
  • [原创](现代Delphi 12指南):[macOS 64bit App开发]: 如何获取自身程序的所在的目录?
  • 【前端基础】8、CSS的选择器
  • Jquery ajax 提交序列化或JSON数据到后台
  • LeetCode算法题(Go语言实现)_61
  • 基于大数据分析的Facebook隐私保护策略
  • 全球电商新势力崛起:拆解Coupang的“韩国速度“与未来棋局
  • ESP32开发之freeRTOS的互斥量
  • C++:扫雷游戏
  • MCP vs Function Call:AI交互的USB-C革命
  • Python实现文件批量改名功能
  • MySQL中隔离级别那点事
  • 国家出口管制工作协调机制办公室部署开展打击战略矿产走私出口专项行动
  • 中国象棋协会坚决支持司法机关依法打击涉象棋行业的违法行为
  • 市自规局公告收回新校区建设用地,宿迁学院:需变更建设主体
  • 中华人民共和国和俄罗斯联邦关于进一步加强合作维护国际法权威的联合声明
  • 中华人民共和国和俄罗斯联邦在纪念中国人民抗日战争、苏联伟大卫国战争胜利和联合国成立80周年之际关于进一步深化中俄新时代全面战略协作伙伴关系的联合声明
  • 谜语的强制力:弗洛伊德与俄狄浦斯