0

How to write Combobox current text in a preexisting text file in hard drive? Here is my code:

void second::on_pushButton_4_clicked()
    {
         QFile file("vik.txt");
         if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
             return;
         QTextStream out(&file);
         out << ui->comboBox_5->currentText() << "\n";
}
László Papp
  • 51,870
  • 39
  • 111
  • 135

2 Answers2

1

Maybe you forgot to close the file

void second::on_pushButton_4_clicked() 
{
    // Get comboBox text value
    QString txt = ui->comboBox_5->currentText();

    // Open file for writing
    QFile file("vik.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);

    // Write in file
    out << txt << "\n";

    // Close file
    file.close();
}
Rémi
  • 525
  • 1
  • 15
  • 26
  • Are you sure the comboBox has a text ? Because I tested this code and it works for me. – Rémi Oct 18 '14 at 08:42
  • 1
    Actually, file closure happens automatically at the end of the function since the file object will be destructed, and the destruction follows the RAII principles, naturally. Furthermore, degrading the OP's code to return after failure in open is a bad idea. Also, it is possible that you have not tested this code with the same execution that the OP had. Vikash may have run the executable differently than you. – László Papp Oct 20 '14 at 12:13
1

You have several issues in your code, let me enumerate them one-by-one:

  • You need this flag for "overwrite" as per your comment:

    QIODevice::Truncate 0x0008 If possible, the device is truncated before it is opened. All earlier contents of the device are lost.

  • More importantly, have you checked whether the method returns after open with some error? If it does, please print out file.errorString() there:

     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
         qDebug() << file.errorString();
         return;
     }
    
  • On the most important note, you are likely facing the issue that the file is not in your current working directory. If the file resides beside the application executable, please change the corresponding line into your code to this:

    QFile file(QCoreApplication::applicationDirPath() + "/vik.txt");
    
László Papp
  • 51,870
  • 39
  • 111
  • 135