您的位置:首页 > 编程语言 > C语言/C++

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

2007-08-30 14:11 363 查看
基于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 );
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: