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.
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.0
and Unkown Error
which is not a useful information.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.
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