I'm attempting to read text into a CString using an LPSTREAM, but it doesn't seem to be working correctly, here is the code that I'm calling:
static HRESULT UTL_ReadStreamTxt(MyStorage* pSrcStg, const char* pszStream, CString* myCStr, int size)
{
HRESULT hrRet = STG_E_INVALIDPARAMETER;
LPSTREAM lpSrc = NULL;
ULONG ul;
TRY
{
USES_CONVERSION;
HRESULT hrSrc = pSrcStg->GetStg()->OpenStream(CT2COLE(strSrc),
NULL,
STGM_READ | STGM_SHARE_EXCLUSIVE,
0,
&lpSrc);
if (hrSrc != NOERROR)
{
hrRet = hrSrc;
}
else
{
hrRet = lpSrc->Read(&myCStr, size, NULL); // Read into CString
}
}
CATCH_ALL(e)
{
hrRet = STG_E_UNKNOWN;
}
END_CATCH_ALL
_AfxRelease((LPUNKNOWN*)&lpSrc);
return hrRet;
}
When it reads into the string, Visual Studio says that the data in the CString is corrupted.
The compound storage's stream contents are the following:
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
I'm not entirely sure I'm using Read() correctly, How do I fix this issue?
The main problem is that you are passing a bad pointer to
Read()
. You are passing the memory address of themyCStr
parameter itself, not the address of theCString
being pointed at, or more accurately, the memory address of a character buffer that theCString
owns. The code compiles only becauseRead()
takes a simplevoid*
pointer to a buffer, and any pointer is implicitly convertible tovoid*
.Also note that
CString
is based onTCHAR
, which maps to eitherchar
orwchar_t
depending on whether you are compiling your project for ANSI/MBCS or Unicode. So, reading from the stream directly into aCString
will only work correctly if:the stream contains ANSI characters and
TCHAR
maps tochar
.the stream contains UTF-16 characters and
TCHAR
maps towchar_t
.If the stream's character type does not match the character type used by
CString
, you would have to first read the stream into an intermediate buffer and then convert that toTCHAR
before it can be stored in theCString
.Try something more like this: