Important: Please read the Qt Code of Conduct -

Write data in TXT

  • Hello everyone.
    First of all thanks for helping me and reading this post.

    I would like to write a std::map data in a .TXT.

    I write this code:

    void MainWindow::on_Save_TXT_button_clicked()
        QString file_save = QFileDialog::getSaveFileName(this, "Guardar TXT", "/home", "files TXT (*.txt)");
            if(!file_save.isEmpty()) //If the user have choosen a file then:
                QFile file_s(file_save); //The QFile class can read and write files. Here we do that namefile will be QFile type with name file.
                //TODO SAVE THE DATA MAP

    With that, the user can specify the file name and path.
    But the problem appears when I use fopen because file_save is not a FILE it is a QString.
    So how can I use that with fopen, fprinf and fclose?

    Thanks a lot.

  • Lifetime Qt Champion

    Why try to mix QFile and old c, fopen fwrite etc?
    You can do it all with Qt classes

    #include <QString>
    #include <QFile>
    #include <QDebug>
    #include <QTextStream>
    int main(int argc, char **argv)
        /* Try and open a file for output */
        QString outputFilename = "Results.txt";
        QFile outputFile(outputFilename);;
        /* Check it opened OK */
            qDebug() << argv[0] << "- Error, unable to open" << outputFilename << "for output";
            return 1;
        /* Point a QTextStream object at the file */
        QTextStream outStream(&outputFile);
        /* Write the line to the file */
        outStream << "Victory!\n";
    // u write ur members of the map.
        /* Close the file */
        return 0;

  • @mrjj Thanks a lot my friend.
    But how can I acces to spaces and \n in QTextStream?
    Because I need a \n in each line.

    so like this:

    maybe with void QTextStream::setFieldWidth(int width)?

    Thanks a lot again.

  • Lifetime Qt Champion


    outStream << "line1" << "\n" << "line2" << "\n";

    and space is just " ".

    Or do I misunderstand what you ask?

  • @mrjj Thanks a lot my friend. It works really fine!!!!!!!!

  • Lifetime Qt Champion

    Super :)
    The best benefit of using a QTextStream is that
    most of Qt classes have overload the << so they can just be saved.

    Note: Be careful with pointers
    QWidget *w;

    stream << w; will write the address
    stream << *w; will write the object (if object have << defined)

  • @mrjj Yes!!! I was careful with that and It worked really fine! Thanks again!

Log in to reply