c风格文件io
int main(int argc, char * argv[])
{
FILE * fp = fopen(data_file.c_str(), "rb");
if (!fp) {
printf("failed to open data file '%s'\n\n", data_file.c_str());
return 2;
}
size_t total_packets = 0;
uint64_t ending_packet_time = 0;
while (!feof(fp)) {
PktHead pkthd;
auto bytes = fread(&pkthd, 1, sizeof(pkthd), fp);
if (bytes == 0) {
break;
}
if (bytes < sizeof(pkthd)) {
printf("invalid packet head size read: %lu\n", bytes);
break;
}
ending_packet_time = pkthd.SendTime;
if (pkthd.MessageCount > 0) {
auto timestr = TimeToStr(pkthd.SendTime);
MessageHead msghd;
for (auto i=0; i<pkthd.MessageCount; i++) {
bytes = fread(&msghd, 1, sizeof(msghd), fp);
if (bytes < sizeof(msghd)) { // file end?
break;
}
auto bodysize = msghd.MessageSize-sizeof(msghd);
if (is_filtered_msg(msghd.MessageType)) {
unique_ptr<char> buf(new char[bodysize]);
bytes = fread(buf.get(), 1, bodysize, fp);
if (bytes < bodysize) {
break;
}
HandleMessage(msghd.MessageType, buf.get(), timestr);
} else {
fseek(fp, bodysize, SEEK_CUR);
}
}
}
total_packets++;
}
fclose(fp);
printf("total packets read: %lu, ending packet time: %s\n", total_packets, TimeToStr(ending_packet_time).c_str());
return 0;
}
cpp风格文件io
bool foo(const std::string& path, uint64_t nmsgs) {
std::ifstream in(path, std::ios::binary);
if (!in.is_open()) {
printf("cannot open file %s\n", path.c_str());
return false;
}
std::string filename = extract_file_name(path);
std::string output = filename + '.' + std::to_string(nmsgs);
std::ofstream out(output, std::ios::binary);
if (!out.is_open()) {
printf("create output file %s failed\n", output.c_str());
return false;
}
MessageHead head;
while (nmsgs-- && in.read(reinterpret_cast<char*>(&head), sizeof(head))) {
std::string buf(head.MessageSize, 0);
memcpy(&buf[0], &head, sizeof(head));
if (!in.read(&buf[sizeof(head)], head.MessageSize - sizeof(head))) {
printf("read message body failed\n");
return false;
}
if (!out.write(buf.data(), buf.size())) {
printf("failed to write data\n");
return false;
}
}
// out.close(); // flush to disk
printf("generate binary file %s ok, remain %lu\n", output.c_str(), nmsgs + 1);
return true;
}