めいくりぷとのブログ

技術的なことをまったりと。

メモリからファイルを作成する。

BOOL CreateFileFromMemoryA(_In_ LPCSTR lpFileName, _In_reads_bytes_(nSize) LPCVOID lpBuffer, _In_ SIZE_T nSize)
{
	INT nLength = MultiByteToWideChar(CP_ACP, 0, lpFileName, -1, NULL, 0);
	if (nLength == 0)
		return FALSE;

	std::unique_ptr<WCHAR> wszBuffer(new WCHAR[nLength]);
	if (MultiByteToWideChar(CP_ACP, 0, lpFileName, nLength, wszBuffer.get(), nLength) == 0)
		return FALSE;

	return CreateFileFromMemoryW(wszBuffer.get(), lpBuffer, nSize);
}

BOOL CreateFileFromMemoryW(_In_ LPCWSTR lpFileName, _In_reads_bytes_(nSize) LPCVOID lpBuffer, _In_ SIZE_T nSize)
{
	DWORD	dwNumberOfBytesToWritten;
	DWORD	dwRestOfSize;
	HANDLE	hFile;
	LPBYTE	pBuffer;
	BOOL	bResult;
	
	bResult 	= FALSE;
	hFile		= CreateFile(lpFileName,
		GENERIC_WRITE, FILE_SHARE_WRITE,
		NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);	

	if (hFile != INVALID_HANDLE_VALUE)
	{
		dwNumberOfBytesToWritten = 0;
		dwRestOfSize	= nSize;
		pBuffer		= (LPBYTE)lpBuffer;

		while (TRUE)
		{
			WriteFile(hFile, pBuffer, dwRestOfSize, &dwNumberOfBytesToWritten, NULL);
			if (dwNumberOfBytesToWritten <= 0)
				break;

			pBuffer		+= dwNumberOfBytesToWritten;
			dwRestOfSize	-= dwNumberOfBytesToWritten;

			if (!bResult)
				bResult = TRUE;
		}

		CloseHandle(hFile);
	}

	return bResult;
}