我正处于 Python 的幼虫阶段和 C++ 的 pre-egg 阶段,但我正在努力做到最好,特别是“不要重复自己”的原则。
我有一个要打开的多通道原始文件格式,带有一个主要的 ascii 标头,其中的字段可表示为字符串和整数(始终编码为用空格填充的字符)。第二部分是 N 个标头,其中 N 是主标头的一个字段,每个标头本身都有更多的文本和数字字段(编码为 ascii),指的是实际 16 位多通道流的长度和大小构成文件的其余部分。
到目前为止,我在 C++ 中有这个工作代码:
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <map>
using namespace std;
struct Header {
string version;
string patinfo;
string recinfo;
string start_date;
string start_time;
int header_bytes;
string reserved;
int nrecs;
double rec_duration;
int nchannels;
};
struct Channel {
string label;
string transducertype;
string phys_dim;
int pmin;
int pmax;
int dmin;
int dmax;
string prefiltering;
int n_samples;
string reserved;
};
int main()
{
ifstream edf("/home/helton/Dropbox/01MIOTEC/06APNÉIA/Samples/Osas2002plusQRS.rec", ios::binary);
// prepare to read file header
Header header;
char buffer[80];
// reads header fields into the struct 'header'
edf.read(buffer, 8);
header.version = string(buffer, 8);
edf.read(buffer, 80);
header.patinfo = string(buffer, 80);
edf.read(buffer, 80);
header.recinfo = string(buffer, 80);
edf.read(buffer, 8);
header.start_date = string(buffer, 8);
edf.read(buffer, 8);
header.start_time = string(buffer, 8);
edf.read(buffer, 8);
stringstream(buffer) >> header.header_bytes;
edf.read(buffer, 44);
header.reserved = string(buffer, 44);
edf.read(buffer, 8);
stringstream(buffer) >> header.nrecs;
edf.read(buffer,8);
stringstream(buffer) >> header.rec_duration;
edf.read(buffer,4);
stringstream(buffer) >> header.nchannels;
/*
cout << "'" << header.version << "'" << endl;
cout << "'" << header.patinfo << "'" << endl;
cout << "'" << header.recinfo << "'" << endl;
cout << "'" << header.start_date << "'" << endl;
cout << "'" << header.start_time << "'" << endl;
cout << "'" << header.header_bytes << "'" << endl;
cout << "'" << header.reserved << "'" << endl;
cout << "'" << header.nrecs << "'" << endl;
cout << "'" << header.rec_duration << "'" << endl;
cout << "'" << header.nchannels << "'" << endl;
*/
// prepare to read channel headers
int ns = header.nchannels; // ns tells how much channels I have
char title[16]; // 16 is the specified length of the "label" field of each channel
for (int n = 0; n < ns; n++)
{
edf >> title;
cout << title << endl; // and this successfully echoes the label of each channel
}
return 0;
};
我已经不得不发表一些评论:
- 我选择使用 struct 是因为格式规范是硬编码的;
- 我没有遍历主要的头字段,因为在我看来要读取的字节数和类型相当随意;
- 既然我成功地获得了每个通道的标签,我实际上将为每个通道的字段创建结构,这些字段本身可能必须存储在地图中。
我的(希望是直截了当的)问题是:
“我应该担心偷工减料以使这种代码更‘Pythonic’(更抽象,更少重复),还是这不是 C++ 中的工作方式?”
许多 Python 布道者(就像我自己一样,因为我喜欢它)强调了它的易用性和所有这些。所以,我会想知道我是在做愚蠢的事情还是只做正确的事情,但由于 C++ 的本质,我不会那么“自动”。
谢谢阅读
赫尔顿