Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi chars are now stored with 2 bytes rather than 1 in typed binary files. How can I still read my old files?

I maintain a Delphi program which uses typed binary files as its native file format. After upgrading from Turbo Delphi to Delphi 2010, all chars in the record type being stored started being stored with 2 bytes rather than one.

The data types being stored are char and array[1..5] of char.

So before, part of the file looked like:

4C 20 20 20 4E 4E 4E 4E

Now it looks like:

4C 00 20 00 20 00 20 00 4E 00 4E 00 4E 00 4E 00

First of all, why did this happen in the first place?

Secondly, how can I still read my files, keeping in mind that there are now old files and new files floating around in the universe?

I will monitor this question obsessively after lunch. Feel free to ask for more information in comments.

like image 315
Instance Hunter Avatar asked Jul 29 '10 16:07

Instance Hunter


1 Answers

This happened when the default string type was changed from AnsiString to UnicodeString in Delphi 2009. Sounds like you were writing strings to the file. Redeclare them in the record as AnsiString and it should work fine.

Same goes for char. The original char was an AnsiChar, one byte per character. Now the default char is a WideChar, which is a UTF-16 char, 2 bytes per character. Redeclare your char arrays as arrays of AnsiChar and you'll get your old file style back.

As for being aware that both styles exist, that's a mess. Unless there's something like a version number in the file that's been changed when you upgraded your Delphi version, I suppose the only thing you can do is scan for 00 bytes in the character data and then have it read in either a AnsiChar or a WideChar version of the record based on whether it finds it.

like image 142
Mason Wheeler Avatar answered Oct 16 '22 01:10

Mason Wheeler