文件处理

#include "my_file.h"

//将文件内容复制到指定文件
int mycopy(const char *filename)
{
 ifstream infile(filename, ios::binary);
 ofstream outfile("TRACE.txt", ios::binary);
 
 if (!infile.is_open() || !outfile.is_open())
 {
  return FAILURERETURN;
 }

 //推断文件大小
 int b = infile.tellg();
 infile.seekg(0, ios::end);
 int e = infile.tellg();
 int len = e - b;
 
 if (len > 0)
 {
  infile.seekg(0, ios::beg);
  char *buf = new char[BUFLEN]();
  if (buf == NULL)
  {

   outfile.close();
   infile.close();
   return FAILURERETURN;
  }
  while (len > 0)
  {
   if (len >= BUFLEN){
    infile.read(buf, BUFLEN);
    outfile.write(buf, BUFLEN);
    len -= BUFLEN;
   }else{
    infile.read(buf, len);
    outfile.write(buf, len);
    len -= len;
   }
  }
  delete []buf;
 }

 outfile.close();
 infile.close();

 return SUCESSRETURN;
}

//将文件内容复制到内存
int mycopybuf(const char *filename, char **buf)
{
 ifstream infile(filename, ios::binary);

 if (!infile.is_open())
 {
  return FAILURERETURN;
 }

 //推断文件大小
 int b = infile.tellg();
 infile.seekg(0, ios::end);
 int e = infile.tellg();
 int len = e - b;

 if (len > 0)
 {
  infile.seekg(0, ios::beg);
  *buf = new char[len+1]();
  if (*buf == NULL){

     infile.close();

     return FAILURERETURN;
  }
  if (!infile.read(*buf, len)){
   infile.close();
   return FAILURERETURN;
  }
 }

 infile.close();
 return SUCESSRETURN;
}


 

posted on 2019-05-12 14:24  xfgnongmin  阅读(85)  评论(0编辑  收藏  举报

导航