Trying to open and read a .txt file, but it deletes the actual text from the original file
-
I have a problem with my code which is the following:
void Quiz::on_actionSelect_Questionnaire_triggered() { QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), "/Users/katwagner/Documents/Programming 2/Assignment/Quizzes", "All Files (*.*);;Text File (*.txt)"); QFile file(filename); if(!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("File Not Open"),"File Cannot Be Opened"); } QTextStream in(&file); QRegularExpression re("Name: "); QString title = in.readLine(); title.remove(re); ui->label_4->setText(title); file.flush(); file.close(); }
It does not show the line on the label, and it deletes all text from the original selected file. Any idea?
-
@windygrass32 said in Trying to open and read a .txt file, but it deletes the actual text from the original file:
if(!file.open(QFile::WriteOnly | QFile::Text))
That's what you open the file for ...
-
@windygrass32 Open the file for reading, not writing. QFile::ReadOnly.
-
@windygrass32 said in Trying to open and read a .txt file, but it deletes the actual text from the original file:
In addition to what others pointed out regarding the file mode you need to use, please be aware that your ward is useless. You check for file not being open Ok, and log the situation, but you still go on and use the non-open file with the stream.
QFile file(filename); if(!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("File Not Open"),"File Cannot Be Opened"); } QTextStream in(&file) ... ...
-
@mpergand said in Trying to open and read a .txt file, but it deletes the actual text from the original file:
In fact I'm suprised that the file is emptied
Doc: QIODevice::WriteOnly: The device is open for writing. Note that, for file-system subclasses (e.g. QFile), this mode implies Truncate unless combined with ReadOnly, Append or NewOnly.