#include
#include
#include
#include
#include
#include
#define SIZE 8196
typedef struct _file MYFILE;
struct _file{
int fd;
char * buf;
int len;
int start;
int end;
int flag;
};
MYFILE * myfopen(char * filename, char * mode)
{
MYFILE * fp = malloc(sizeof(MYFILE));
int read_flag = 0;
fp->flag = 0;
if(!strcmp(mode, "r"))
{
fp->flag |= O_RDONLY ;
read_flag = 1;
fp->fd = open(filename, fp->flag);
}
if(!strcmp(mode, "w"))
{
if(read_flag == 1)
{
fp->flag -= O_RDONLY;
fp->flag |= O_RDWR;
}
else
fp->flag |= O_WRONLY ;
fp->flag |= O_CREAT;
fp->flag |= O_TRUNC;
fp->fd = open(filename, fp->flag, 0644);
}
fp->buf = malloc(SIZE);
fp->len = SIZE;
fp->start = 0;
fp->end = 0;
return fp;
}
void myfclose(MYFILE * fp)
{
if(fp->flag & O_WRONLY)
{
write(fp->fd, fp->buf + fp->start, fp->end - fp->start);
}
free(fp->buf);
free(fp);
}
int myfread(char * buf, int size, int count, MYFILE * fp)
{
int ret = 0;
int ret1 = 0;
if(fp->end == fp->start)
{
ret = read(fp->fd, fp->buf, SIZE);
fp->end = ret;
fp->start = 0;
}
int read_num = size * count;
int data_num = fp->end - fp->start;
if(read_num <= data_num)
{
memcpy(buf, fp->buf + fp->start, read_num);
fp->start += read_num;
ret1 = count;
}
else
{
memcpy(buf, fp->buf + fp->start, data_num);
fp->start += data_num;
buf += data_num;
read_num -= data_num;
ret = read(fp->fd, buf, read_num);
ret1 = (ret + data_num) / size;
}
return ret1;
}
int myfwrite(char * buf, int size, int count, MYFILE * fp)
{
int ret;
int ret1;
if(fp->end == fp->len)
{
write(fp->fd, fp->buf, fp->len);
fp->end = 0;
}
int write_num = size * count;
int data_num = fp->len - fp->end;
if(write_num <= data_num)
{
memcpy(fp->buf + fp->end, buf, write_num);
fp->end += write_num;
ret1 = count;
}
else
{
memcpy(fp->buf + fp->end, buf,data_num);
fp->end += data_num;
buf += data_num;
write_num -= data_num;
ret = write(fp->fd, buf, write_num);
ret1 = (ret + data_num) / size;
}
return ret1;
}
int main(int argc, char * argv[])
{
if(argc != 3)
{
fprintf(stderr, "Usage: %s src dec \n", argv[0]);
return -1;
}
// "w" : O_WRONLY | O_CREAT | O_TRUNC
// "r" : O_RDONLY
MYFILE * fpr = myfopen(argv[1], "r");
MYFILE * fpw = myfopen(argv[2], "w");
char buf[200] = {};
int ret;
while(1)
{
ret = myfread(buf, 1, 200, fpr);
if(ret == 0)
break;
// printf(buf);
// memset(buf, 0, 200);
printf("ret = %d \n", ret);
myfwrite(buf, 1, ret, fpw);
}
myfclose(fpr);
myfclose(fpw);
}
阅读(622) | 评论(0) | 转发(0) |