PDA

View Full Version : read ascii files with different column counts



pospiech
5th November 2009, 15:11
I have the following code for reading an ascii file with 7 columns:


while (!in.atEnd())
{

in >> GratingType
>> newEntry.delay
>> newEntry.period
>> newEntry.phase
>> newEntry.chirp
>> newEntry.powerIndex
>> newEntry.powerScale;

VariationList.push_back(newEntry);
}

However I also have files with a similar structure, but only 4 columns


while (!in.atEnd())
{

in >> GratingType
>> newEntry.delay
>> newEntry.period
>> newEntry.phase;

VariationList.push_back(newEntry);
}


How can I find out how many columns my file has?

If I read a 4 column file with the 7 column version the data structure is read wrong.

This is a very basic question, and maybe not really Qt and more C++ related, but I do not really know how to start looking for a clever solution.

squidge
5th November 2009, 15:35
Read each line into a string and then check the length of the string? Or perhaps check for column delimiters?

pospiech
6th November 2009, 08:36
Ok, that should work with this code:


int numberOfValues = 0;
if (!in.atEnd()) {
QString line = in.readLine();
QStringList list = line.split("\t");
numberOfValues = list.size();
}
while (!in.atEnd())
{
in >> GratingType
>> newEntry.delay
...

However, how do I reset the 'in' variable to beginning of file?

squidge
6th November 2009, 10:38
What class are you using? QTextStream? QFile? Something else?

pospiech
6th November 2009, 11:42
What class are you using? QTextStream? QFile? Something else?

I solved it now using the following code:


QFile file(filename);
if (!file.open(QIODevice::ReadOnly))
{
return;
}
QTextStream in(&file);

GratingVariationListEntryDef newEntry;

int numberOfValues = 0;
if (!in.atEnd()) {
QString line = in.readLine();
QStringList list = line.split("\t");
numberOfValues = list.size();
in.seek(0);
}
while (!in.atEnd())
{
switch (numberOfValues)
{
case 4:
in >> GratingType
>> newEntry.delay
>> newEntry.period
>> newEntry.phase;
break;
case 5:
...


It works, however from the docs it is not obvious that 'seek(0);' is what I was looking for. I had tried 'reset()', but that changed nothing so that I do not even know what it does.

squidge
6th November 2009, 12:42
reset() does what you want, but since you are using QTextStream also, that buffers the file and so reset() doesn't give the expected result.

This is actually fully described in the documentation.