我正在将二进制数据读取到一个结构中,它工作得很好。这是代码:
#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;
}
前几行输出如下:
(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
我的问题是:是否可以将结构中的C风格字符数组替换为C++字符串?如果是这样,您能否举例说明我将如何做到这一点。非常感谢!
最佳答案
该代码似乎旨在将以特定二进制格式序列化的数据读取为 TaqIdx
格式。您当然可以修改阅读器以提供不同格式的数据(包括 std::string
s),但您要么必须重写阅读器,要么在加载后进行转换。或者,您可以使用完全不同的数据格式,但这可能与您拥有的文件不兼容。
关于c++ - 如何在结构中使用字符串而不是 char 数组来读取二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5588845/