We help IT Professionals succeed at work.

Read line by line

obad62
obad62 asked
on
Hi there ,

I have this code which reads file correctly, the file has many line how can I alter this code to be read for examlp 10 lines only and print that in text browser .

In java (because I am java progarmmer ) we use .next method what about here !!!?

void Widget::on_pushButton_clicked() 
{ 
QFile file("file.txt"); 
if(!file.exists()){ 
ui ->textBrowser->append("file is not exists"); 
} 
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){ 
ui ->textBrowser->append("file is not open"); 
return ; 
} 
QTextStream in(&file); 
while (!in.atEnd()) 
{ 
QString content = in.readLine(); 
ui->textBrowser->append(content); 
} 
}

Open in new window

Comment
Watch Question

Top Expert 2012
Commented:
You can simply add another loop condition, e.g.
unsigned int max_lines = 10;
unsigned int lines_read = 0;

while (!in.atEnd() && lines_read < max_lines) 
{ 
  QString content = in.readLine(); 
  ui->textBrowser->append(content); 
  lines_read++; // increase line counter
} 

Open in new window

jkr
Top Expert 2012

Commented:
BTW, a 'for' loop might be another option, e.g.
unsigned int max_lines = 10;

for( unsigned int line_count = 0; line_count < max_lines && !in.atEnd(); line_count++) 
{ 
  QString content = in.readLine(); 
  ui->textBrowser->append(content); 
} 

Open in new window