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? 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. 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. 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
?
精彩评论