#define BUFFER_SIZE 1024
#define PARTIONFREE_MINSIZE 0

int CopyFile2File(const char* srcFileName,  const char* destFileName)
{
 if(srcFileName == NULL || destFileName == NULL)
 {
  return -1;
 }

 int srcFile = -100,destFile = -100;  
 int iRealReadLen = 0;
 int iIndex = -1;
 unsigned char buff[BUFFER_SIZE];
 char tmpFileName[128] = {0};
 char cNewName[32] = {0}; 
 CWebString newDestFileName = destFileName;
 iIndex = newDestFileName.find_last_of("/") + 1;
 if( iIndex < (newDestFileName.find_last_of("\\") + 1))
 {
  iIndex = newDestFileName.find_last_of("\\") + 1;
 }

 //目表文件的目录
 CWebString strDestFilePath = newDestFileName.substr(0, iIndex); 
 //目表文件的文件名
 CWebString strDestFileName = newDestFileName.substr(iIndex, newDestFileName.length()); 
 int iCount = 0;
 srand((unsigned int) time(NULL));

 //拼接临时文件名,防止原来文件在写入的时候被覆盖,如果空间不足,则会将原有文件删除
 do{
  if(++iCount > 10)
  {
   return -2;     
  }
  sprintf(cNewName, "%04d", rand());//snprintf(cNewName, 4, "%04d", rand());  
  sprintf(tmpFileName, "%s%s", strDestFilePath.c_str(), cNewName);
 }while(access(tmpFileName, F_OK) == 0);
 
 //以只读方式打开源文件
 srcFile=open(srcFileName, O_RDONLY);
 //以只写方式打开目标文件,如此文件不存在创建该文件,权限为644 
 destFile=open(tmpFileName, O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);

 if(srcFile < 0||destFile < 0)
 {
  WEBDEBUG_INFO("Open file error");
  return -3;
 } 
 //read函数返回每次读出的字节数
 while( (iRealReadLen = read(srcFile, buff, sizeof(buff)) ) > 0
    &&   GetPartionFreeSize(tmpFileName) > PARTIONFREE_MINSIZE)
 {
  write(destFile,buff,iRealReadLen);  
 }

 close(destFile);
 close(srcFile);
 
 //判断是否由于剩余空间不足,造成文件读取结束,若是,则删除文件
 if( PARTIONFREE_MINSIZE >= GetPartionFreeSize(tmpFileName) )
 {
  WEBDEBUG_INFO("Lack of space");
  remove(tmpFileName);  
  return -3;
 }
 //目标文件已经存在,则删除文件
 if(access(destFileName, F_OK) == 0)
 {  
  remove(destFileName);
 }
 if(rename(tmpFileName, destFileName) < 0)
 {
  return -4;
 }

 return 0;
}

 

//功能:获取某个分区剩余空间大小,主要应用于获取配置分区/yealink/config/剩余空间大小
long GetPartionFreeSize(const char *path)
{
 struct statfs s;
 long partion_free_size;

 statfs(path, &s);
 partion_free_size = s.f_bsize*s.f_bfree;

return partion_free_size

 }

posted on 2014-08-18 16:45  叶城宇  阅读(326)  评论(0编辑  收藏  举报