潜在地,您可以定义 FixedLengthFieldsRecord 类,以便该类本身强制执行正确的记录长度,但允许每个记录中的任意数量的字段。实现此目的的一种可能的好方法是让 CONSTRUCTOR 从文件中读取下一条记录。
该类(减去一些必要的错误检查,您可以添加)可以以与以下类似的方式编写(该类假定您在创建此类的对象之前阅读了文件的第一行):
using namespace std;
class FixedLengthFieldsRecord
{
public:
FixedLengthFieldsRecord(int const recordLength, istream & s); // Set the length of the record in the constructor
bool IsEmpty() const;
int FieldCount() const; // variable number of fields allowed; but LENGTH of record is enforced (see below)
bool IsValidRecord(); // Does the record contain the correct number of bytes?
string GetField(int const index) const; // This could throw an exception if the record is not valid
protected:
// Could have sophisticated functions here to replace fields, remove fields, reorder fields, etc.
// This section contains the actual implementation.
private:
vector<string> fields; // The vector contains a VARIABLE number of fields
bool is_empty;
bool is_valid;
int const record_length; // This contains the LENGTH of the record; it is set in the constructor and cannot be changed
// The following variable and function store (and access) ALL the records
static vector<FixedLengthFieldsRecord> records;
static read(int numRec, FixedLengthFieldsRecord & rec);
}
FixedLengthFieldsRecord::FixedLengthFieldsRecord(int const recordLength_, istream & s)
: record_length(recordLength)
{
// pseudocode provided here
// this functionality could be factored into other functions that are called by the constructor
is_valid = true;
is_empty = ReadFirstByte(s); // ReadFirstByte (not shown) reads first byte of current line and returns true if it indicates an empty record
if (!is_empty)
{
string field;
int currentRecordLength = 0;
while (ReadNextField(s, field)) // ReadNextField() returns true if another field was read from the line (i.e., not end-of-line
{
currentRecordLength+= field.length();
}
if (currentRecordLength != record_length)
{
is_valid = false;
}
if (currentRecordLength > record_length)
{
break;
}
if (is_valid)
{
fields.push_back(field);
}
}
if (is_valid)
{
records.push_back(*this); // not efficient, nor thread safe - deep copy occurs here
}
}
bool FixedLengthFieldsRecord::IsEmpty()
{
return is_empty();
}
bool FixedLengthFieldsRecord::IsValidRecord()
{
return is_valid;
}
string FixedLengthFieldsRecord::GetField(int const index)
{
if (!is_valid)
{
// throw an exception, or return an empty string
}
if (index < 0 || index >= fields.size())
{
// throw an exception, or return an empty string
}
return fields[index];
}
FixedLengthFieldsRecord::read(int numRec, FixedLengthFieldsRecord & rec)
{
if (numRec < 0 || numRec >= records.size())
{
// throw an exception, or just return
}
rec = records[numRec];
}