-7

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 explain this weird behavior?

0

2 Answers 2

1

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.

3
  • My bad, typo. It wasn't in the original code, checked now for sure in some backup. Sorry for misleading, edited now. Jun 30, 2011 at 9:14
  • ReleaseBuffer might be the thing, it was never called in the original code - you think it might cause such behavior as I described in my question? Jun 30, 2011 at 9:16
  • @ShadowWizard: I know I once had errors when I forgot the call to ReleaseBuffer but I don't remember what happened.
    – ur.
    Jun 30, 2011 at 11:26
0

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;
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.