How to update a txt file.
-
Hello!
I'm doing a code that updates paths in three QLineEdit with QFileDialog :: getExistingDirectory command and these paths are saved in a txt file. I need to update each QLineEdit and save these changes to my txt file.
ps: The old path that has been updated, should not appear in my text file
My GUI looks like this here:
!http://doc.qt.digia.com/qq/qq08-qlineedit.png!But I can not correctly save my updates in a txt file. Look at my code to update one of my QLineEdit:
@void MainWindow::on_toolButton_4_clicked()
{QString directory = QFileDialog::getExistingDirectory(this, tr("Find Files"), QDir::currentPath()); if(!directory.isNull()){ ui->lineEdit_4->setText(directory); } QFile file(_filename); QTextStream out(&file); QTextStream in(&file); if(!file.open(QFile::ReadWrite | QFile::Text)){ qDebug() << "could not open file for writing"; return; } QString line1 = in.readLine(); QString line2 = in.readLine(); QString line3 = in.readLine(); out << directory << "\n"; out << line2 << "\n"; out << line3 << "\n";
}
@ -
Ohhh, I did this too a while back. BUT: I had two different dialogs, one for reading, one for writing.
Anyway, what I did to write in the file, is this:
@
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "",
tr("Text Files (.txt);;C++ Files (.cpp *.h)"));QFile file(fileName);
if(!file.open(QIODevice::WriteOnly)){
QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
return;
} else {
QTextStream stream(&file);
stream<<"First name: "<<fName;
stream<<"\r\nLast name: "<<lName;
stream<<"\r\nAccount Number: "<<accNum;
stream<<"\r\nCurrent Balance: "<<nBal;
stream.flush();
file.close();
}
@I cant really find out what is wrong with yours though. What you could try, is where your second if statement is (line 12), you could add the else statement. That could work, I would try it if I were you. That, and you should close the file when you are done with it. If my suggestion doesn't work, refer to "this":http://qt-project.org/doc/qt-4.8/gettingstartedqt.html , it is a while down the page, actually, the last example on the page.
BTW: Why is the window seem so old, like, windows 98?
-
I'm not doing a program like this image I posted, is just to try to explain what I'm doing.
The problem with my code are the paths that are added at the end of my txt file in sequence and not replaced as I want. -
I achieve resolve the problem this way:
@void MainWindow::on_toolButton_4_clicked()
{QString directory = QFileDialog::getExistingDirectory(this, tr("Find Files"), QDir::currentPath()); if(!directory.isNull()){ ui->lineEdit_4->setText(directory); } QFile file(_filename); QTextStream out(&file); QTextStream in(&file); if(!file.open(QFile::ReadWrite | QFile::Text)){ qDebug() << "could not open file for writing"; return; }else{ QString item2 = ui->lineEdit_5->text(); QString item3 = ui->lineEdit_6->text(); out << directory << "\r\n"; out << item2 << "\r\n"; out << item3 << "\r\n";
}
}@