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<<2

typedef 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 *fp
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值