简体   繁体   English

如何在结构中使用字符串而不是char数组来读取二进制数据

[英]How do I use a string in a struct instead of a char array for reading binary data

I am reading binary data into a struct, which is working just fine. 我正在将二进制数据读取到一个结构中,这很好。 Here is the code: 这是代码:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct TaqIdx {
  char symbol[10];
  int tdate;
  int begrec;
  int endrec;
}__attribute__((packed));

int main()
{
  ifstream fin("T201010A.IDX", ios::in | ios::binary);

  if(!fin) {
    cout << "Cannot open file."  << endl;
    return 1;
  }

  int cnt = 0;
  TaqIdx idx;

  while(fin.read((char *) &idx,sizeof(idx))) {
    if(!fin.good()) {
      cout << "A file error occurred." << endl;
      return 1;
    }

    idx.symbol[10] = '\0';
    cout << "(" << idx.symbol << ", " << idx.tdate << ", " 
         << idx.begrec << ", " << idx.endrec << ") "
         << cnt++ << endl;
  }

  fin.close();

  return 0;
}

The first few lines of output are the following: 输出的前几行如下:

(A         , 20100864, 1, 35981) 0
(AA        , 20100864, 35982, 89091) 1
(AAPR      , 20100864, 89092, 89093) 2
(AACC      , 20100864, 89094, 89293) 3
(AADR      , 20100864, 89294, 89301) 4
(AAI       , 20100864, 89302, 99242) 5
(AAME      , 20100864, 99243, 99252) 6
(AAN       , 20100864, 99253, 102275) 7
(AANA      , 20100864, 102276, 102280) 8
(AAON      , 20100864, 102281, 102592) 9

My question is this: is it possible to replace the C-style character array in the structure with a C++ string? 我的问题是:是否可以用C ++字符串替换结构中的C样式字符数组? If so, can you provide an example of how I would do that. 如果是这样,您能否提供一个示例说明我该如何做。 Many thanks! 非常感谢!

The code appears to be designed to read data serialized with a particular binary format into the TaqIdx format. 该代码似乎旨在将以特定二进制格式序列化的数据读取为TaqIdx格式。 You could certainly modify the reader to supply the data in a different format (including std::string s) , but you'd either have to rewrite the reader or convert after it had been loaded. 您当然可以修改读取器以提供其他格式的数据(包括std::string ),但是您必须重写读取器或在读取器装入后进行转换。 Alternatively you could use an entirely different format for the data but that might not be compatible with the files you have. 另外,您可以对数据使用完全不同的格式,但是可能与您拥有的文件不兼容。

I can't "comment everywhere" yet, so I apologize for this being kind of out of standard protocol around these parts. 我还不能“到处评论”,因此,对于这些部分的标准协议,我深表歉意。 Why doesn't this break? 为什么不休息呢?

idx.symbol[10] = '\\0';

The length of symbol is 10, won't having __attribute__((packed)) in there put a null byte into the first byte of tdate ? symbol的长度是10,不会在其中将__attribute__((packed))放入空字节到tdate的第一个字节中tdate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM