所以我有一个二进制文件,我正在读取一个2字节的字值,值是Int16 = 43140,但每当我在Delphi中读取它时它返回43104,我写了代码在C#中读取它测试并且它正确读取它仅在Delphi中读取不正确,看起来0和4因某种原因而移位。
TMyHeader= packed record
Value1 :String[20];
Value2 :Word; // Is 43140 but reading as 43104
Value3 :Word;
Value4 :Word; // Is 43140 but reading as 43104
end;
FileRead (fhandle, header, sizeof(MyHeader));
答案 0 :(得分:0)
您的代码不使用流阅读器,并且问题完全不可能是阅读文件。以下是使用TFileStream
成功读取和写入记录而不以任何方式更改值的示例。 (显然,您必须先将TestFile
常量更改为指向系统上有效的可写位置。)
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes;
type
TMyHeader = packed record
Value1: String[20];
Value2: Word;
Value3: Word;
Value4: Word;
end;
var
MyHeader: TMyHeader;
Stream: TFileStream;
const
TestFile = 'E:\TempFiles\Testheader.bin';
begin
// Initialize the record
MyHeader.Value1 := 'Testing One Two';
MyHeader.Value2 := 43140;
MyHeader.Value3 := 12345;
MyHeader.Value4 := 43140;
// Show what it contains. The `[]` brackets are to clearly delimit Value1
WriteLn(Format('Before write: [%s] %d %d %d',
[MyHeader.Value1, MyHeader.Value2, MyHeader.Value3, MyHeader.Value4]));
// Write it to the stream.
Stream := TFileStream.Create(TestFile, fmCreate, fmShareDenyNone);
try
Stream.Write(MyHeader, SizeOf(TMyHeader));
finally
Stream.Free;
end;
// Clear the contents of MyHeader before reading back, and show the empty values
FillChar(MyHeader, SizeOf(TMyHeader), 0);
WriteLn(Format('Before read: [%s] %d %d %d',
[MyHeader.Value1, MyHeader.Value2, MyHeader.Value3, MyHeader.Value4]));
Stream := TFileStream.Create(TestFile, fmOpenRead, fmShareDenyNone);
try
Stream.Read(MyHeader, SizeOf(TMyHeader));
finally
Stream.Free;
end;
// Output what we've read back in to verify it is correct
WriteLn(Format('After read: [%s] %d %d %d',
[MyHeader.Value1, MyHeader.Value2, MyHeader.Value3, MyHeader.Value4]));
Readln;
end.