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

基础IO -- 简单封装库(文件操作)

1.mystdio.c (函数实现)

#include "mystdio.h"myFILE* my_fopen(const char *path, const char *flag)
{int flag1 = 0;int iscreate = 0;mode_t mode = 0666;if(strcmp(flag, "r") == 0){flag1 = (O_RDONLY);}else if(strcmp(flag, "w") == 0){flag1 = (O_WRONLY | O_CREAT | O_TRUNC);iscreate = 1;}else if(strcmp(flag, "a") == 0){flag1 = (O_WRONLY | O_CREAT | O_APPEND);iscreate = 1;}else{}int fd = 0;if(iscreate)fd = open(path, flag1, mode);elsefd = open(path, flag1);if(fd < 0) return NULL;myFILE *fp = (myFILE*)malloc(sizeof(myFILE));if(!fp) return NULL;fp->fileno = fd;fp->flags = FLUSH_LINE;fp->cap = LINE_SIZE;fp->pos = 0;return fp;
}void my_fflush(myFILE *fp)
{write(fp->fileno, fp->cache, fp->pos);fp->pos = 0;
}ssize_t my_fwrite(myFILE *fp, const char *data, int len)
{// 写入操作本质是拷贝, 如果条件允许,就刷新,否则不做刷新memcpy(fp->cache+fp->pos, data, len); //肯定要考虑越界, 自动扩容 这里简易版,不做处理fp->pos += len;if((fp->flags&FLUSH_LINE) && fp->cache[fp->pos-1] == '\n'){my_fflush(fp);}return len;
}void my_fclose(myFILE *fp)
{my_fflush(fp);close(fp->fileno);free(fp);
}

2.mystdio.h (函数声明)

#pragma once#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>#define LINE_SIZE 1024
#define FLUSH_NOW  1
#define FLUSH_LINE 2
#define FLUSH_FULL 4struct _myFILE
{unsigned int flags;int fileno;// 缓冲区char cache[LINE_SIZE];int cap;int pos; // 下次写入的位置
};typedef struct  _myFILE myFILE;myFILE* my_fopen(const char *path, const char *flag);
void my_fflush(myFILE *fp);
ssize_t my_fwrite(myFILE *fp, const char *data, int len);
void my_fclose(myFILE *fp);

3.testfile.c (测试)

#include "mystdio.h"
#include <string.h>
#include <stdio.h>
#include <unistd.h>#define FILE_NAME "log.txt"int main()
{myFILE *fp = my_fopen(FILE_NAME, "w");if(fp == NULL) return 1;const char *str = "hello bit";int cnt = 10;char buffer[128];while(cnt){sprintf(buffer, "%s - %d\n", str, cnt);my_fwrite(fp, buffer, strlen(buffer)); // strlen()+1不需要cnt--;sleep(1);}my_fclose(fp);return 0;
}

测试为利用模拟的fopen、fwrite、fflush以及fclose去实现向log.txt文件中每隔一秒写入1行字符串,共十秒


http://www.mrgr.cn/news/61046.html

相关文章:

  • CRM客户关系管理系统:全方位提升销售效能的利器
  • 「后人类视角下的哲学思考:技术与人性的新边界」
  • 【modbus协议】libmodbus库移植基于linux平台
  • AI大模型宝典:掌握未来的三本关键开发书籍,大模型书籍宝典
  • 【对比学习】正交阵/酉矩阵,对称矩阵/Hermite矩阵,正交相似对角化/奇异值分解的内在联系
  • 【架构-36】常见的各类锁的特点
  • 【高阶数据结构】红黑树的插入(超多精美图解+完整代码)
  • 【文心智能体 | AI大师工坊】如何使用智能体插件,完成一款旅游类智能体的开发,来体验一下我的智能体『​​​​​​​背包客』
  • 数据传输的事务定义有哪三种?
  • (N-154)基于springboot酒店预订管理系统
  • 【python】OpenCV—Tracking(10.3)—GOTURN
  • 树莓派开发相关知识三PWM控制转速
  • leetcode 1261.在受污染的二叉树中查找元素
  • 雷池社区版compose文件配置讲解--fvm
  • JVM 调优深度剖析:优化 Java 应用的全方位攻略(一)
  • 什么是道德?
  • 红黑树(C++实现)
  • 清仓和斩仓有什么不一样?
  • 鲲泰新闻丨构筑融通的坚实智造之基!神州鲲泰亮相第二届中国航空工艺设备博览会
  • 【Java】方法的使用