下面這段代碼,是用C的標準庫檔案編寫的拷貝檔案的例子程式。可移植性較強,稍加修改就可以在Windows平台下的任何C/C++編譯器下正常運行。
global.cpp----------------------------------------------------------------
#include "global.h"
#include "stdio.h"
#include "windows.h"
void DoEvents()
{
MSG msg;
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
//參數表:目標檔案、源檔案、百分比(可在對話方塊類的Timer訊息的處理函數中更新進度條)
bool copyfile(char * dst,char *src,long &perc)
{
const long BUF_SIZE = 40960;
unsigned long filelen=0;
unsigned char buf[BUF_SIZE];
long i,j,k;
perc =0;
FILE * fpd= fopen(dst,"wb");
FILE * fps= fopen(src,"rb");
if (NULL==fpd || NULL==fps)
{
if (NULL!=fpd)fclose(fpd);
if (NULL!=fps)fclose(fps);
return false;
}
fseek(fps, 0, SEEK_END);
filelen=ftell(fps);
fseek(fps,0,SEEK_SET);
j = filelen / BUF_SIZE;
k = filelen % BUF_SIZE;
for (i =0 ; i< j ; i++)
{
fread(buf,BUF_SIZE,1,fps);
fwrite(buf,BUF_SIZE,1,fpd);
if (0==(i & 0xf)){perc =100 * i / j ; DoEvents();}
}
fread(buf,k,1,fps);
fwrite(buf,k,1,fpd);
perc=100;
fclose(fps);
fclose(fpd);
return true;
}
-------------------------------------------------------------------------------