- // UpdateResource_Console.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- //including the file & Updating the resource data
- void ImportFile(void)
- {
- HANDLE hFile;
- DWORD dwFileSize,
- dwBytesRead;
- LPBYTE lpBuffer;
- hFile = CreateFile("C://WINDOWS//system32//calc.exe", GENERIC_READ,
- 0,
- NULL,
- OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL,
- NULL);
- if (INVALID_HANDLE_VALUE != hFile)
- {
- dwFileSize = GetFileSize(hFile, NULL);
- lpBuffer = new BYTE[dwFileSize];
- if (ReadFile(hFile, lpBuffer, dwFileSize, &dwBytesRead, NULL) != FALSE)
- {
- // do something with lpBuffer here //Updating the resource data
- HANDLE hResource;
- hResource = BeginUpdateResource("C://Documents and Settings//mjs//"
- "桌面//资料//RightNowDoing//UpdateResource_MFC//"
- "Debug//UpdateResource_MFC.exe", FALSE);
- if (NULL != hResource)
- {
- char* p = MAKEINTRESOURCE(104);
- if (UpdateResource(hResource,
- RT_RCDATA,
- MAKEINTRESOURCE(104),
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //使用系统缺省语言
- (LPVOID) lpBuffer,
- dwFileSize) != FALSE)
- {
- EndUpdateResource(hResource, FALSE);
- }
- }
- }
- delete [] lpBuffer;
- CloseHandle(hFile);
- }
- }
- //Extracting the data & Saving the data to a file
- void ExtractFile(void)
- {
- HMODULE hLibrary;
- HRSRC hResource;
- HGLOBAL hResourceLoaded;
- LPBYTE lpBuffer;
- hLibrary = LoadLibrary("C://Documents and Settings//mjs//"
- "桌面//资料//RightNowDoing//UpdateResource_Console//"
- "Debug//UpdateResource_Console.exe");
- if (NULL != hLibrary)
- {
- char* p = MAKEINTRESOURCE(104);
- hResource = FindResource(hLibrary, MAKEINTRESOURCE(104), RT_RCDATA);
- LPVOID lpMsgBuf;
- FormatMessage(
- FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL,
- GetLastError(), //获得错误代码
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
- (LPTSTR) &lpMsgBuf, //错误代码对应的文字描述
- 0,
- NULL
- );
- // Process any inserts in lpMsgBuf.
- // ...
- // Display the string.
- MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION );
- // Free the buffer.
- LocalFree( lpMsgBuf );
- if (NULL != hResource)
- {
- hResourceLoaded = LoadResource(hLibrary, hResource);
- if (NULL != hResourceLoaded)
- {
- lpBuffer = (LPBYTE) LockResource(hResourceLoaded);
- if (NULL != lpBuffer)
- {
- // do something with lpBuffer here
- DWORD dwFileSize,dwBytesWritten;
- HANDLE hFile;
- dwFileSize = SizeofResource(hLibrary, hResource);
- hFile = CreateFile("C://WINNT//TEMP//calc2.exe",
- GENERIC_WRITE,
- 0,
- NULL,
- CREATE_ALWAYS,
- FILE_ATTRIBUTE_NORMAL,
- NULL);
- if (INVALID_HANDLE_VALUE != hFile)
- {
- WriteFile(hFile, lpBuffer, dwFileSize, &dwBytesWritten, NULL);
- CloseHandle(hFile);
- }
- }
- }
- }
- FreeLibrary(hLibrary);
- }
- }
- int main(int argc, char* argv[])
- {
- ImportFile();
- ExtractFile();
- return 0;
- }
以上资料,均来自网上,记录下来,方便以后查看。把资源导入EXE,和从EXE导出文件时,有一点要留意,不能把一个资源导入到一个正在运行的程序,可以从一个正在运行的程序中导出资源。也就是要注意读写冲突。