I have a "sequence.dat" file that contains "1"s and "-1"s in a vertical representation (i.e.: each element is in a single line).. I am trying to read the file as follow:

QFile sequence("Sequences.dat");
sequence.open(QIODevice::ReadOnly);
QByteArray data = sequence.readAll(); 
for(int i=0; i<29; i++){        
    signedNo[i] = data[i]; // debugging breaking point
}
sequence.close();

however, at the debugging breaking point, the QByteArray "data" contains "1, -, 1, \n" instead of "1,-1" ...

is there is away to read the whole line at once and not each byte individually ? and ... if there is not, how to tell the "readAll" function to avoid the "\n" (it is not an optimal solution because I want also to read "-1" and not "- and 1" separately)

有帮助吗?

解决方案

QFile::readAll() returns a byte array which contains each and every byte of the file as a separate element.

For your use case, you need to read the file line by line.

The QFile documentation shows some approaches how to do this, for example:

 QVector<int> elements;

 QFile sequence("Sequences.dat");
 if (!sequence.open(QIODevice::ReadOnly | QIODevice::Text))
     return;

 QTextStream in(&sequence);
 while (!in.atEnd()) {
     QString line = in.readLine();
     elements.append(line.toInt());
 }

Despite the fact that this sample is from the Qt documentation, I would recommend to check the return value from in.readLine() which returns a null QString when the end of the file has been reached, instead of using atEnd().

其他提示

You could read line by line, and you could process it right after you read the line:

 i = 0;
 while (!sequence.atEnd()) {
     QByteArray line = sequence.readLine();
     signedNo[i] = line[i];
     i++;
 }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top