Question

I am working with Delphi Prism and creating and writing into binary file using BinaryWriter as follows.

method TUnit.Write(bw:BinaryWriter);
var
    i:Integer;
begin
    bw.write(ord(uType));
    bw.Write(ord(State));
    bw.Write(Address);
    bw.Write(SubAddress);

    for i:=1 to 20 do
        bw.Write(fDefs[i]);
end;

My question to you is this. Does the write method write line per line or bytes after bytes or character after character without line feed or carriage return?

The reason I am asking this question is because I am confused when it comes to writing and reading string without specific numbers of characters like array of characters.

For instance:

method WritetoFile;
var
    x:integer;
    thestr:string;
begin
    BinaryWriter thefile := new BinaryWriter(File.Create("test.dat"));
    thefile.write(thestr);
    thefile.write(x);
    thefile.Close;
end;

method ReadFromFile;
var
   x:integer;
   thestr:string;
begin
   BinaryReader thefile := new BinaryReader(File.OpenRead("test.dat"));
   thestr:=thefile.ReadString;
   x:=thefile.ReadInt32;
   thefile.Close;
end;

That's how I wrote my program and it seems to work fine, but as I said I am confused.

How does it know how many bytes or characters length to read or write when it is a string data type without giving it a specific numbers of length to read?

Was it helpful?

Solution

Does BinaryWriter "Write method" work the same as Writeln method from Delphi?

No it does not.

How does it know how many bytes or characters length to read or write when it is a string data type without giving it a specific numbers of length to read?

In many ways you don't really need to know how BinaryWriter and BinaryReader does it. You are using it correctly. You just need to pair each Write() call with a matching ReadXXX() call of the appropriate type.

The documentation does describe the underlying binary file format. You don't need to write or read the length of the string since the Binary I/O classes do exactly that on your behalf.

A length-prefixed string represents the string length by prefixing to the string a single byte or word that contains the length of that string. This method first writes the length of the string as a UTF-7 encoded unsigned integer, and then writes that many characters to the stream by using the BinaryWriter instance's current encoding.

So you can safely write a string which contains linefeeds and when it is read those linefeeds will be preserved.

OTHER TIPS

No it does not. You want to use StreamWriter for that, which has WriteLine and Write methods that do what you want. The binaryReader/Writer classes use a prefix integer for the Length, then write the data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top