C++, load text from resource or disk
代码
BOOL LoadFileResource(const wstring& strName, HMODULE hDll,
int resourceID, string& outputBuf)
{
HGLOBAL hResourceLoaded; // handle to loaded resource
HRSRC hRes; // handle/ptr to res. info.
char *lpResLock; // pointer to resource data
DWORD dwSizeRes;
hRes = FindResourceW(hDll, MAKEINTRESOURCE(resourceID), strName.c_str());
hResourceLoaded = LoadResource(hDll, hRes);
lpResLock = (char *) LockResource(hResourceLoaded);
dwSizeRes = SizeofResource(hDll, hRes);
char* pBuf = new char[dwSizeRes+1];
if ( NULL == pBuf )
{
cout << "Alloc memory for storing the xml schema file failed." << endl;
return FALSE;
}
ZeroMemory(pBuf, dwSizeRes+1);
memcpy(pBuf, lpResLock, dwSizeRes);
outputBuf.clear();
outputBuf.assign(pBuf);
delete [] pBuf;
return TRUE;
}
BOOL LoadDiskFile(const wstring& fileName, string& outputBuf)
{
BOOL retv = FALSE;
FILE* schemaFile = NULL;
if (fileName.empty() || (0 != _wfopen_s(&schemaFile, fileName.c_str(), L"r+t")))
return retv;
fseek(schemaFile, 0, SEEK_END);
long fileLen = ftell(schemaFile);
char* pFileBuf = new char[fileLen];
if ( NULL == pFileBuf )
{
fclose(schemaFile);
return retv;
}
memset(pFileBuf, 0, fileLen);
fseek(schemaFile, 0 , SEEK_SET );
long readCount = (long)fread(pFileBuf, 1, fileLen, schemaFile);
if ( feof(schemaFile) && 0 != readCount )
{
outputBuf.assign(pFileBuf);
retv = TRUE;
}
fclose(schemaFile);
delete []pFileBuf;
return retv;
}
int resourceID, string& outputBuf)
{
HGLOBAL hResourceLoaded; // handle to loaded resource
HRSRC hRes; // handle/ptr to res. info.
char *lpResLock; // pointer to resource data
DWORD dwSizeRes;
hRes = FindResourceW(hDll, MAKEINTRESOURCE(resourceID), strName.c_str());
hResourceLoaded = LoadResource(hDll, hRes);
lpResLock = (char *) LockResource(hResourceLoaded);
dwSizeRes = SizeofResource(hDll, hRes);
char* pBuf = new char[dwSizeRes+1];
if ( NULL == pBuf )
{
cout << "Alloc memory for storing the xml schema file failed." << endl;
return FALSE;
}
ZeroMemory(pBuf, dwSizeRes+1);
memcpy(pBuf, lpResLock, dwSizeRes);
outputBuf.clear();
outputBuf.assign(pBuf);
delete [] pBuf;
return TRUE;
}
BOOL LoadDiskFile(const wstring& fileName, string& outputBuf)
{
BOOL retv = FALSE;
FILE* schemaFile = NULL;
if (fileName.empty() || (0 != _wfopen_s(&schemaFile, fileName.c_str(), L"r+t")))
return retv;
fseek(schemaFile, 0, SEEK_END);
long fileLen = ftell(schemaFile);
char* pFileBuf = new char[fileLen];
if ( NULL == pFileBuf )
{
fclose(schemaFile);
return retv;
}
memset(pFileBuf, 0, fileLen);
fseek(schemaFile, 0 , SEEK_SET );
long readCount = (long)fread(pFileBuf, 1, fileLen, schemaFile);
if ( feof(schemaFile) && 0 != readCount )
{
outputBuf.assign(pFileBuf);
retv = TRUE;
}
fclose(schemaFile);
delete []pFileBuf;
return retv;
}
将想法付诸于实践,借此来影响他人是一个人存在的真正价值