1

我正在尝试从二进制文件中读取数据。一个数据块有 76 个字节长(这随块中间的 2 字节“主要数据项”的数量而变化)。第一个数据是4个字节,第二个是4个字节,然后是一堆2字节的主数据项,最后是2个2字节的数据。

在此处输入图像描述

基于这个 Delphi 示例,我学习了如何使用以下代码读取文件:

short AShortInt; // 16 bits
int AInteger; // 32 bits
try
{
 infile=new TFileStream(myfile,fmOpenRead); // myfile is binary
 BR = new TBinaryReader(infile, TEncoding::Unicode, false);
 for (int rows = 0; rows < 5; rows++) {  // just read the first 5 blocks of data for testing
  AInteger = BR->ReadInt32(); // read first two 4 byte integers for this block
  AInteger = BR->ReadInt32();
  for (int i = 0; i < 32; i++) { // now read the 32 2-byte integers from this block
   AShortInt = BR->ReadInt16();
  }
  AShortInt = BR->ReadInt16(); // read next to last 2-byte int
  AShortInt = BR->ReadInt16(); // read the last 2-byte int
}
delete infile;
delete BR;
Close();
}
catch(...)
{
 delete infile;  // closes the file, doesn't delete it.
 delete BR;
 ShowMessage("Can't open file!");
 Close();
}

但是,我想做的是使用一个 76 字节宽的缓冲区来读取整个块,然后从该缓冲区中挑选各种数据。我根据这个问题整理了以下代码,我可以将整个数据块读入缓冲区。

UnicodeString myfile = System::Ioutils::TPath::Combine(System::Ioutils::TPath::GetDocumentsPath(), "binaryCOM.dat");
TFileStream*infile=0;
try
{
 infile=new TFileStream(myfile,fmOpenRead);
 const int bufsize=76;
 char*buf=new char[bufsize];
 int a = 0;
 while(int bytesread=infile->Read(buf,bufsize)) {
   a++; // just a place to break on Run to Cursor
 }
 delete[]buf;
}
catch(...)
{
  delete infile;  
  ShowMessage("Can't open file!");
  Close();
}

但我不知道如何从缓冲区中的字节中拼凑出子集。有没有办法连接 字节?所以我可以将一个数据块读入一个 76 字节的缓冲区,然后在下面做这样的事情?

unsigned int FirstDatum = buf[0]+buf[1]+buf[2]+buf[3];  // concatenate the 4 bytes for the first piece of data

这将是一个在 C++Builder 10.3.2 中构建的适用于 Win32、iOS 和 Android 的 FMX 应用程序。

4

1 回答 1

0

这是我使用 Remy 的建议修改的代码TMemoryStream

UnicodeString myfile = System::Ioutils::TPath::Combine(System::Ioutils::TPath::GetDocumentsPath(), "binaryCOM.dat");

TMemoryStream *MS=0;
TBinaryReader *BR=0;
std::vector<short> myArray;
short AShortInt;
int AInteger;
int NumDatums = 32; // the variable number of 2-byte main datums

try
{
  MS = new TMemoryStream();
  MS->LoadFromFile(myfile);
  BR = new TBinaryReader(MS, TEncoding::Unicode, false);
  for (int rows = 0; rows < 5; rows++) {  // testing with first 5 blocks of data
    AInteger = BR->ReadInt32(); // read first two 4 byte integers
    AInteger = BR->ReadInt32(); // here
    for (int i = 0; i < NumDatums; i++) {  // read the main 2-byte data
      AShortInt = BR->ReadInt16();
      myArray.push_back(AShortInt); // push it into vector
    }
    AShortInt = BR->ReadInt16(); // read next to last 2-byte int
    AShortInt = BR->ReadInt16(); // read the last 2-byte int
    // code here to do something with this block of data just read from file
  }
}
delete MS;
delete BR;
}
catch(...)
{
 delete MS;  
 delete BR;
 ShowMessage("Can't open file.");
}
于 2019-09-24T19:27:17.107 回答