-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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208

2 Answers2

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.

ur.
  • 2,890
  • 1
  • 18
  • 21
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;
sarat
  • 10,512
  • 7
  • 43
  • 74
  • There is no file, I'm reading from parallel port from a machine. – Shadow The GPT Wizard Jun 30 '11 at 10:27
  • Any valid handle is treated as a file. It can be a disk file, device or anything. If you're reading from a file, it's better to go by a fixed size buffer but still CString is not adviced See http://msdn.microsoft.com/en-us/library/aa450604.aspx – sarat Jun 30 '11 at 13:39