.net - 德尔福棱镜 : Does BinaryWriter "Write method" work the same as Writeln method from Delphi?

标签 .net delphi delphi-prism binaryreader binarywriter

我正在使用 Delphi Prism 并使用 BinaryWriter 创建和写入二进制文件,如下所示。

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;

我向你提出的问题是这样的。 write 方法是否逐行写入或逐个字节写入或逐个字符写入而不换行或回车?

我问这个问题的原因是因为我在编写和读取没有特定数量的字符(例如字符数组)的字符串时感到困惑。

例如:

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;

这就是我编写程序的方式,它似乎工作正常,但正如我所说,我很困惑。

当它是字符串数据类型时,它如何知道要读取或写入多少字节或字符长度而不给它指定要读取的长度?

最佳答案

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

不,没有。

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?

在很多方面,您实际上并不需要了解 BinaryWriterBinaryReader 是如何做到这一点的。您正在正确使用它。您只需将每个 Write() 调用与相应类型的匹配 ReadXXX() 调用配对即可。

documentation确实描述了底层的二进制文件格式。您不需要写入或读取字符串的长度,因为二进制 I/O 类完全代表您执行此操作。

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.

因此,您可以安全地编写包含换行符的字符串,并且在读取该字符串时,这些换行符将被保留。

关于.net - 德尔福棱镜 : Does BinaryWriter "Write method" work the same as Writeln method from Delphi?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7362111/

相关文章:

.net - 在Powershell中运行外部程序的替代方法

.net - 从 'Sandbox Environment' 中的 .Net 应用程序加载程序集

delphi - 抄字典的正确方法是什么?

c# - 是否可以在 iPhone 和 OS X 上不使用 NIB 文件来创建窗口?

.net - 如何创建 DateTime 的动态数组?

c# - 通过 C# .NET 访问 Gmail Drive

c# - Entity Framework 数据库表关联

delphi - CEF(Chromium 嵌入式框架)与 DEP(数据执行保护)

delphi - Graphics32 : Pan with mouse-drag, 用鼠标滚轮缩放鼠标光标

xna - 在 Delphi Prism 中做 XNA