views:

335

answers:

1

Going through some of my older Delphi projects and upgrading them to D2009, as I find this version a great improvement (Generics.Collections - wow! ;)) to all previous releases, I encounter various problems. This one I managed to solve but the solution does not seem half as elegant as I believe it could be. (Note, I haven't written Delphi code for about three years now and even back then it was rather amateurish hacking than in-depth understanding of what's going on).

My code would have a TFileStream and read from it. The files were written previously by my older Delphi app in a way that the first three characters in the file would be CTR to recognise the file type as valid. The reader would read in the first three bytes into an array of chars (and here's the problem, now that sizeof(char) is 2 bytes) and then treat this array as string to see if it reads 'CTR'.

var ...
buffer: array[0..2] of char;
begin
...
InStream.read(buffer, 3);
if buffer <>'CTR' then begin ShowMessage('Not a valid file!'); exit; end;
...

This will compile and it used to work but now buffer is practically 6 bytes long and therefore does not equal 'CTR' ever.

I fixed this by changing the buffer to array[0..2] of byte and I introduced some more local variables to do the following:

for b in buffer do s := s + chr(b); //notice the for..in loop now available in D2009
if s<>'CTR'...

So basically I turn the individual bytes to a string and then do the compare, but there must be a more straightforward way to do this. Can you please shed some light on this issue?

+13  A: 

You can set your buffer to

var
  buffer: array[0..2] of AnsiChar;

and you'll read in the exact same thing as before.

Nick Hodges
worked as a charm :) thanks
Peter Perháč
IMHO, <code>array[0..2] of Byte</code> matches the intention better.
Moritz Beutel