How can QT read data from a file and assign it to a variable?

In Qt, you can use the QFile class to read file data and assign it to a variable. Here is an example code to read file data and assign it to a variable:

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

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

    QString filename = "path/to/file.txt"; // 文件路径
    QFile file(filename);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "Unable to open file";
        return 1;
    }

    QTextStream in(&file);
    QString fileData = in.readAll(); // 读取文件数据并赋值给变量

    file.close();

    // 在这里可以使用fileData变量进行后续处理

    return a.exec();
}

In the above code, a QFile object is first created and then the file is opened using the open() function. Within the open() function, the file is opened in read-only mode using QIODevice::ReadOnly, and QIODevice::Text is used to inform Qt to handle the file as text. If the file fails to open, exceptions can be handled by checking the return value.

Next, pass the QFile object to QTextStream, and read the entire content of the file by calling the readAll() function and assigning it to the variable fileData. Finally, close the file.

By using this method, you can assign file data to a variable and use it in subsequent processing.

bannerAds