ReadFile weird behavior when buffer is CString
I have inherited code using ReadFile
Windows API method to read single byte from parallel port in a loop.
The code passed CString
instance as the buffer argument, and 1 as the number of bytes to read, something like this:
CString inBuffer = "";
bResult = ReadFile(hCom, inBuffer.GetBuffer(1), 1, &nBytesRead, NULL);
allData += inBuffer.GetBuffer(1);
It worked for long time with this code, but sometimes caused weird problems for example input sent from the machine as "AV01000" was read as "AkVk0k1k0k0k0" - somehow some random character was added after each character read.
Took me long time to figure the source of this behavior, and after changing the code to:
char buffer = '\0';
bResult = ReadFile(hCom, &buffer, 1, &nBytesRead, NULL);
allData += buffer;
It worked flawlessly, reading the exact data sent by the machine.
Is this some kind of buffer overflow in the internal code of CString
? If not, what might ex开发者_StackOverflowplain this weird behavior?
Remove the address operator:
bResult = ReadFile(hCom, inBuffer.GetBuffer(1), 1, &nBytesRead, NULL);
Also: Don't forget the matching call to ReleaseBuffer. And for adding that character
allData += inBuffer;
should be sufficient.
First thing is that, CString acts according to the encoding you're chosen for the project. If your project is Unicode format, each character is stored in the CString character represented in two bytes(WCHAR). If the file and object are having same encoding, it will work fine. (Also you can determine the file encoding by analyzing BOM character in the beginning)
The buffer size you're passing is 1. If you still want to use the CString object, please pass the proper size for the buffer by passing file's length by calling GetFileSize() API.
I suggest you to use the buffer allocated method.
like
char* pReadbuff = new char[sizeoffile];
ReadFile(..);
CString objStr = pReadbuff;
delete pReadbuff;
精彩评论