Windows File API Samples Part 2: CopyFileEx

Problem: You need to copy file with process bar showing.

Solution: You can leverage the progressRoutine with CopyFileEx().

Sample Code:

#include "common.h"

using namespace std;

DWORD CALLBACK progressRoutine(
	LARGE_INTEGER TotalFileSize,
	LARGE_INTEGER TotalBytesTransferred,
	LARGE_INTEGER StreamSize,
	LARGE_INTEGER StreamBytesTransferred,
	DWORD dwStreamNumber,
	DWORD dwCallbackReason,
	HANDLE hSourceFile,
	HANDLE hDestinationFile,
	LPVOID lpData
)
{
	SYSTEMTIME end;
	GetLocalTime(&end);
	LONGLONG msecs = subtract(&end, (SYSTEMTIME*) lpData);
	cout << TotalBytesTransferred.QuadPart << "/" << TotalFileSize.QuadPart  << " bytes copied in " << " " << msecs  << "  ms ...." << endl;
	return PROGRESS_CONTINUE;
}

int _tmain(int argc, TCHAR** argv)
{
	if(argc<3)
	{
		_tprintf(_T("usage: copyfile source dest\n"));
		return -1;
	}

	BOOL b = FALSE;

	SYSTEMTIME begin;
	GetLocalTime(&begin);

	//fstream debug("debug.log", fstream::in | fstream::out | fstream::app );
	//debug.open("debug.log", ios::app);

	Debugger debugger;
	debugger.logBegin(COPY_FILE);

	BOOL result = CopyFileEx(argv[1], argv[2], &progressRoutine , &begin, &b,  COPY_FILE_FAIL_IF_EXISTS);   

	debugger.logEnd(COPY_FILE);
	debugger.close();

	cout << ( result?"success":"failed" ) << endl;

	return 0;

}
Digg This
Reddit This
Stumble Now!
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)