C++:
BOOL pCopyFile(LPWSTR SourceFilePath, LPWSTR DestinationFilePath)
{
BOOL Return = FALSE;
if (!SourceFilePath || !DestinationFilePath)
{
#ifdef __DEBUG
OutputDebugStringW(L"Utils::pCopyFile - error occured. One of the passed parameters is NULL.");
#endif
return Return;
}
if (GetFileAttributesW(DestinationFilePath) != INVALID_FILE_ATTRIBUTES)
{
#ifdef __DEBUG
OutputDebugStringW(L"Utils::pCopyFile - error occured. Destination file already exists.");
#endif
return Return;
}
HANDLE SourceFileHandle = CreateFileW(SourceFilePath, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
if (SourceFileHandle == INVALID_HANDLE_VALUE)
{
#ifdef __DEBUG
OutputDebugStringW(L"Utils::pCopyFile - error occured. Can't obtain handle of the source file.");
#endif
goto Cleanup;
}
HANDLE DestinationFileHandle = CreateFileW(DestinationFilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
if (DestinationFileHandle == INVALID_HANDLE_VALUE)
{
#ifdef __DEBUG
OutputDebugStringW(L"Utils::pCopyFile - error occured. Can't obtain handle of the destination file.");
#endif
goto Cleanup;
}
HANDLE FileMappingHandle = CreateFileMappingW(SourceFileHandle, NULL, PAGE_READONLY, 0, 0, NULL);
if (!FileMappingHandle)
{
#ifdef __DEBUG
OutputDebugStringW(L"Utils::pCopyFile - error occured. Can't create file mapping.");
#endif
goto Cleanup;
}
LPVOID FileData = MapViewOfFile(FileMappingHandle, FILE_MAP_READ, 0, 0, 0);
if (!FileData)
{
#ifdef __DEBUG
OutputDebugStringW(L"Utils::pCopyFile - error occured. Can't map file to memory.");
#endif
goto Cleanup;
}
DWORD BytesWritten = 0;
if (!WriteFile(DestinationFileHandle, FileData, GetFileSize(SourceFileHandle, NULL), &BytesWritten, NULL))
{
#ifdef __DEBUG
OutputDebugStringW(L"Utils::pCopyFile - error occured. Can't write data to the destination file.");
#endif
goto Cleanup;
}
Return = TRUE;
Cleanup:
if (SourceFileHandle)
{
CloseHandle(SourceFileHandle);
}
if (DestinationFileHandle)
{
CloseHandle(DestinationFileHandle);
}
if (FileData)
{
UnmapViewOfFile(FileData);
}
return Return;
}
Последнее редактирование: