QFile - Row Count Problem
-
Hi guys
I have datas in txt file. I want to count how many rows are in the txt file.
data_num.txt
@
10 15,2
12,1 42
...
@@
...
QFile file("datas/data_num.txt");
...
QTextStream in(&file);
...
int rowSize;
while( !in.atEnd()){
rowSize++;
}
@When I debuged the program, I guess I got endless loop. Because my program is waiting something and It crash. Why doesn't the while loop stop?
-
Because inside your loop, you are not doing any file reading. You should read a line per loop iteration.
-
[quote author="Andre" date="1364563689"]Because inside your loop, you are not doing any file reading. You should read a line per loop iteration.[/quote]
Okey. I changed the code but now I cant get the datas from txt. Because "in" locations is atEnd?
@ QString a;
while( !in.atEnd()){
a = in.readLine();
rowSize++;
}...
QString data1, data2;for(int i=0; !in.atEnd(); i++) {
in >> data1 >> data2;accTableColumn1[i] = data1.toDouble(); accTableColumn2[i] = data2.toDouble();
}
@ -
Why don't you combine the two operations in a single loop? That would be much more efficient...
-
I know but there are some codes in second loop which need rowSize.
-
Really? There is no way around that?
Note that reading the input file twice is much slower than iterating over an in-memory structure again to adapt some values...But if you insist: how about you simply move the position back to the beginning of the file after you have measured the number of rows? QIODevice::seek should be what you are looking for there.
-
Yes, you right. I should change my code a little. By the way I fix the error with seek() func. Thanks for quick help:)
@ QString a;
while( !in.atEnd()){
a = in.readLine();
rowSize++;
}
in.seek(0);
...@