gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:58:29 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com