how to read and write to a file in qt c++

#include <QCoreApplication>
#include <QFile>
#include <QTextStream>
#include <QDebug>

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    // Create a QFile object to work with a file named "example.txt"
    QFile file("example.txt");

    // Check if the file can be opened in WriteOnly and Text mode
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "Could not open the file for writing";
        return -1;
    }

    // Create a QTextStream object and associate it with the file
    QTextStream out(&file);

    // Write data to the file using QTextStream
    out << "Hello, this is a sample text.\n";
    out << "This is another line of text.";

    // Close the file
    file.close();

    // Open the file for reading
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Could not open the file for reading";
        return -1;
    }

    // Read data from the file line by line and output to console
    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine();
        qDebug() << line;
    }

    // Close the file
    file.close();

    return a.exec();
}

Explanation:

  1. #include directives: Include necessary headers for working with Qt functionalities.

  2. QCoreApplication: The entry point for Qt-based applications.

  3. QFile file("example.txt"): Create a QFile object named file and associate it with a file named "example.txt".

  4. if (!file.open(QIODevice::WriteOnly | QIODevice::Text)): Check if the file can be opened in WriteOnly and Text mode. If it fails to open, print an error message and return -1.

  5. QTextStream out(&file): Create a QTextStream object named out and associate it with the file for writing data to the file.

  6. Writing data to the file using QTextStream (out << "Hello, this is a sample text.\n"; out << "This is another line of text.";).

  7. file.close(): Close the file after writing.

  8. Reopen the file for reading (if (!file.open(QIODevice::ReadOnly | QIODevice::Text))) and handle errors if it fails to open.

  9. QTextStream in(&file): Create a QTextStream object named in and associate it with the file for reading data from the file.

  10. Reading data from the file line by line using while (!in.atEnd()) and outputting each line to the console using qDebug() << line.

  11. file.close(): Close the file after reading.

  12. return a.exec(): Return the result of the application's event loop execution (required for Qt applications).