c++qtqt5qfile

How to fix QFile open error (unknown error) even though the file exists?


I am trying to open and read a map.dat file using QFile interface, but it won't open that file even though it does exist in the directory.

I am using:

QFile mapDat("/Users/myname/projectname/file.dat");
if (!mapDat.exists()){
    qDebug() << "not exist";
}

QString errMsg;
QFileDevice::FileError err = QFileDevice::NoError;
if (!mapDat.open(QIODevice::ReadOnly) | QFile::Text){
    errMsg = mapDat.errorString();
    err = mapDat.error();
    qDebug() << "could not open it" << err << errMsg;
    return;
}

QTextStream in(&mapDat);
QString mText = in.readAll();
qDebug() << mText;
mapDat.close();

I expect qDebug() << mText to give me something in the console, but it doesn't.

The output is:

could not open it 0 "Unknown error"

which is from the qDebug() line within the if statement.


Solution

  • Your condition is wrong:

    if (!mapDat.open(QIODevice::ReadOnly) | QFile::Text)
    

    This will try to open the file in read-only mode. The result of that is negated (!), and then ORed with QFile::Text (which is != 0). So the condition will always be true.

    You have a simple typo (misplaced parenthesis):

    if (!mapDat.open(QIODevice::ReadOnly | QFile::Text))
                                     //  ^ Bitwise OR of flags for mapDat.open call