Search code examples
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 have tried fopen, ifstream in C++, but they keep telling me the file does not exist even I have added it into resource folder (.qrc). Then I turn to QFile interface, the problem remains. This is a directory problem, I now compromise and use absolute(not the best practice) path and now the file existence problem is solved.
  • Now it still cannot open the file, I use interface's member function to see what are the error code and error message, and I got 0 and Unkown Error which is not a useful information.

I am using:

  • MacOS Mojave 10.14.2.
  • Qt 5.11.3.
  • Compiler: clang_64bit
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