首页 > 代码库 > 文件处理

文件处理

#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)
  {
   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){
   return FAILURERETURN;
  }
  if (!infile.read(*buf, len)){
   infile.close();
   return FAILURERETURN;
  }
 }

 infile.close();
 return SUCESSRETURN;
}