跨盘符文件移动的实现(C语言)

基于C Library的跨盘符文件移动的实现。

首先判定是否为相同盘符下的移动。

如果“是”直接调用库函数::rename即可;如果“不是”必须进行拷贝。

该函数中用到了如下C库函数:

::rename, ::_open, ::_close, ::_read, ::_write, ::_filelength, ::remove

/*
   Function that moves a file.
   Returns non-zero if successful, otherwise zero.
*/
int move( char *srcpath, char *dstpath )
{
   if( srcpath[1]==':' && dstpath[1]==':' && toupper(srcpath[0])!=toupper(dstpath[0]) )
   {
      // different drives, must copy
      char* buf;
      int srcfile, dstfile;
      int res=BUF_SIZE;

      // open source file
      if( !((srcfile = ::_open( srcpath, _O_RDONLY|_O_BINARY ) ) != -1))
         return FALSE;

      // check that destination file does not already exist
      if( !((dstfile = ::_open( dstpath, _O_RDONLY|_O_BINARY ) ) != -1))
         return FALSE;

      // create destination file
      if( !((dstfile = ::_open( dstpath, _O_RDWR|_O_BINARY|_O_CREAT, _S_IREAD|_S_IWRITE ) ) != -1))
         return FALSE;

      // create file copy buffer
      buf=new char[BUF_SIZE];
      if( buf==NULL )
         return FALSE;

      // copy contents of source file to destination file
      while( res > 0 )
      {
         res=::_read( srcfile, buf, BUF_SIZE );
         ::_write( dstfile, buf, res );
      }

      // check resulting file length
      res=::_filelength( srcfile ) == ::_filelength( dstfile );

      // clean up
      delete buf;
      ::_close( srcfile );
      ::_close( dstfile );

      // if copy was OK, remove source file, otherwise remove dest. file
      if( res )
         ::remove( srcpath );
      else
         ::remove( dstpath );
      return res;
   }
   else
      return !::rename( srcpath, dstpath );
}
 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值