Search code examples
qtqfile

QFile error : device not open


I have a code:

int actualSize = 8;
QFile tableFile("C:\\Users\\Ms\\Documents\\L3\\table"+QString::number(actualSize)+".txt");
QTextStream in(&tableFile);
QString oneLine;
oneLine.append(in.readAll());
if(tableFile.exists())
{
    messageLabel->setText(oneLine);
}else
{
    messageLabel->setText("Not open");
}

In the C:\Users\Ms\Documents\L3\ folder, I have a "table8.txt" file. But the messageLabel (which is a QLabel) will have a "Not open" text, oneLine is empty, tableFile.exists() is false, and I got a device not open warning/error.

I tried relative path, like

QFile tableFile("table"+QString::number(actualSize)+".txt");

But none of the methods I come up with was good.


Solution

  • You should be able to use / separators for all QFile-related paths. Open the file before you read it and close it when done.

    int actualSize = 8;
    QFile tableFile("C:/Users/Ms/Documents/L3/table"+QString::number(actualSize)+".txt");
    if(tableFile.exists() && tableFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream in(&tableFile);
        QString oneLine;
        oneLine.append(in.readAll());
        messageLabel->setText(oneLine);
        tableFile.close();
    } else
    {
        messageLabel->setText("Not open");
    }