I have a txt file with 20 lines. I want to output from line 10 - 20 on a QTextBrowser.
I did something like this:
`
QFile file(name);
file.open(QIODevice::ReadOnly|QIODevice::Text);
QTextStream instream(& file);
int linecount_1 = 10;
while(linecount_1<=20)
{
QString line = instream.readLine();
ui->textBrowser->append(line);
++linecount_1;
}
file.close();
I am expecting this to read from line 10 to 20 but I'm wrong this is reading from line 1 to 10!
Can anyone spot what mistake I'm doing here?
You can't just read lines starting from line 10; you have to read all the lines and add a if condition which decides if you want to drop the read input in case you're reading lines >10 or you want to append it in case you're reading lines between 10 and 20.
int linecount_1 = 0;
while(linecount_1<20)
{
QString line = instream.readLine();
if (linecount_1 >= 10)
{
ui->textBrowser->append(newline);
}
++linecount_1;
}
Related
I have to parse a big file with several thousand records. I want to display a progress bar, but I do not know the number of recordings in advance. Do I have to roll over this file twice?
The first to know the number of recording.
The second to perform the treatment
Or is there a more simple way to get the number of records without going through the entire file before I process ?
My code snippet :
void readFromCSV(const QString &filename){
int line_count=0;
QString line;
QFile file(filename);
if(!file.open(QFile::ReadOnly | QFile::Text))
return;
QTextStream in(&file);
while(!in.atEnd()){ //First loop
line = in.readLine();
line_count++;
}
while (!in.atEnd()) { //Second loop
...
line = in.readLine();
process();
...
}
}
Thank you for help
This question is different from the one here : counting the number of lines in a text file
1) The loop process is already done. In this case it is prevention of double shooting.
2) The code is a QT one, not a C++ fonction to add as a redundancy
I think there is no way to count lines without reading the file at least once. To avoid it I wouldn't rely on the number of lines, but rather on how much data I have been read. Here is how I would solve this problem:
QFile file(fileName);
file.open(QFile::ReadOnly | QFile::Text);
const auto size = file.size();
QTextStream in(&file);
while (!in.atEnd()) {
auto line = in.readLine();
// Process line.
// [..]
// Calculate the progress in percent.
auto remains = file.bytesAvailable();
auto progress = ((size - remains) * 100) / size;
printf("progress: %d%%\r", progress);
}
How I can to insert the value from txt file in to the Qlist...
QList<QString> list_StRead;
list_StRead.insert();
I can sorting txt file ... its mean that my file is a line by line. than after the insert to the Qlist I want to write in to Qtabelewidget. How I must to do?? u must to be completely understand. see the img file
tnx for all....
Here is the pseudo code.
Please try it. (Not tested, code written in notepad. excuse me any syntax errors).
//Your list
QList<QString> list_StRead;
//Text stream object read data and insert in list.
QTextStream in(&file);
while (!in.atEnd())
{
QString line = in.readLine(); //read one line at a time
list_StRead.push_back(line);
}
//loop your list
for(int i =0; i<list_StRead.size(); i++)
{
//Add by create your tablewidget item and append it.
YourTableWidget->setItem(rowNumber,colNumber,new QTableWidgetItem(list_StRead.at(i)))
}
For learning purposes, I would like to plot data stored in a text file using QCustomPlot within Qt. The QCustomPlot takes a QVector (double), and when I create the vector by hand (initializing the vector with values), the plotting works. But when I read in the values from the text file, nothing happens. I get no compiler errors and there is no plotting.
I used the code snippets from code example. You can see the code I am using below. I spent a few hours reading through the web, but it was to no avail.
QVector<double> v;
QVector<double> x(20), y(20);
QFile textFile("Data3.txt");
if(textFile.open(QIODevice::ReadOnly))
{
double d;
QTextStream textStream(&textFile);
while (!textStream.atEnd()) {
textStream >> d;
if(textStream.status() == QTextStream::Ok){
v.append(d);
}
else
break;
}
for(int i=0; i<=20; ++i)
{
x[i] = i;
y[i] = v[i];
}
}
QVector<double> myVectorx({0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19});
QVector<double> myVectory({0.5,1,3,5,7,10});
ui->custom2Widget->addGraph();
ui->custom2Widget->graph()->setData(myVectorx, y);
//ui->custom2Widget->graph()->addData(x,y);
ui->custom2Widget->graph()->setPen(QPen(Qt::blue));
ui->custom2Widget->xAxis->setRange(0,25);
ui->custom2Widget->yAxis->setRange(0, 100);
ui->custom2Widget->xAxis->setLabel("Time");
ui->custom2Widget->yAxis->setLabel("CO2 values");
ui->custom2Widget->replot();
The data file looks like this (it is one column, not one after the other in the same row):
315.71
317.45
317.5
317.1
315.86
314.93
313.2
312.66
313.33
I have a question about what a QTextStream is calculating with the pos() method. I assumed it was the number of bytes, but it seems that this might not be the case.
The reason I ask, is that I am processing rows in a file, and once the number of rows read reached some arbitrary number or stream.atEnd() is true, I break out of the loop and save stream.pos() to a qint64* variable. Once the processing is complete, I go back to the file and seek(*filePosition) to get back to my last position and grab more data until stream.atEnd() is true. This works in the sense that can keep track of where I am, but it is very slow calling stream.pos() as is noted in the Qt docs.
What I am attempting is to update the file position after each line is read in an efficient manner. However, it is not working and when the program goes back to read the file again, the position is not correct as the first line it reads starts in the middle of line previously read on the last iteration.
Here is what is have so far:
QTextStream stream(this);
stream.seek(*filePosition);
int ROW_COUNT = 1;
while (!stream.atEnd()) {
QString row = stream.readLine();
QStringList rowData = row.split(QRegExp(delimiter));
*filePosition += row.toUtf8().size();
/*
processing rowData...
*/
if (ROW_COUNT == ROW_UPLOAD_LIMIT) {
break;
}
ROW_COUNT++;
}
/*
close files, flush stream, more processing, etc...
*/
QTextStream::pos returns position in bytes. I see the following problems:
You are not accounting for the line ending character (or 2 characters)
In UTF-8, a single character might take more than 1 byte
Also, why save buffer position after reading each line? This might be faster:
if (ROW_COUNT == ROW_UPLOAD_LIMIT) {
*filePosition = stream.pos();
break;
}
The solution was to create the QTextStream outside of the function and pass it in as a parameter. Doing this allows me to not have to worry about tracking the position on each iteration because I keep the stream in scope until I have completely finished processing the file.
class FeedProcessor {
...
void processFeedFile() {
IntegrationFile file("big_file.txt");
file.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream stream(&file);
while(!stream.atEnd()) {
file.extractFileContents(&stream);
/*
do more processing with file
*/
}
}
...
}
class IntegrationFile : public QFile {
...
void extractFileContents(QTextStream* stream) {
int ROW_COUNT = 1;
while (!stream.atEnd()) {
QString row = stream.readLine();
QStringList rowData = row.split(QRegExp(delimiter));
/*
processing rowData...
*/
if (ROW_COUNT == ROW_UPLOAD_LIMIT) {
break;
}
ROW_COUNT++;
}
/*
close files, flush stream, more processing, etc...
*/
}
...
}
I have a text file. I need to read it to a QStringList. there are no line seperators. I mean each line in the text file is in a new line. So is there anyway i can do this?
I assume that every line should be a separate string in the list. Use QTextStream::readLine() in a cycle and on each step append the returned value to the QStringList. Like this:
QStringList stringList;
QFile textFile;
//... (open the file for reading, etc.)
QTextStream textStream(&textFile);
while (true)
{
QString line = textStream.readLine();
if (line.isNull())
break;
else
stringList.append(line);
}
QFile TextFile;
//Open file for reading
QStringList SL;
while(!TextFile.atEnd())
SL.append(TextFile.readLine());
If the file isn't too big, read the whole content into a QString and then split() it into a QStringList.
I like using the QRegExp version to handle linefeed from different platforms:
QStringList sList = s.split(QRegExp("(\\r\\n)|(\\n\\r)|\\r|\\n"), QString::SkipEmptyParts);
I like my code to be fully indented/paranthesized with obvious variable names (they may take longer to type but are much easier to debug) so would do the following (but changing "myTextFile" and "myStringList" to more sensible names, such as "employeeListTextFile")
QFile myTextFile;
QStringList myStringList;
if (!myTextFile.open(QIODevice::ReadOnly))
{
QMessageBox::information(0, "Error opening file", myTextFile.errorString());
}
else
{
while(!myTextFile.atEnd())
{
myStringList.append(myTextFile.readLine());
}
myTextFile.close();
}
The below code reads the file
QFile File("/file_path");
if(!File.open(QIODevice::ReadOnly));
{
qDebug("Error");
}
QTextStream in(&File);
while(!in.atEnd())
{
qDebug()<<ReadAll;
ReadAll=in.readAll();
}
File.close();
Now the file is closed, now split the new line i.e \n here \r is carriage return
List= ReadAll.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);