Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1298742
  • 博文数量: 548
  • 博客积分: 7597
  • 博客等级: 少将
  • 技术积分: 4224
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-15 13:21
个人简介

嵌入式软件工程师&&太极拳

文章分类

全部博文(548)

文章存档

2014年(10)

2013年(76)

2012年(175)

2011年(287)

分类: LINUX

2011-03-04 22:53:32

#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);
}

 
阅读(614) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~