基于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 );
}