I am trying to read a simple text file using QFile (Qt5), but it strangely doesn't work. Below is my code.
QFile*file = new QFile("gh.txt");
if(file->open(QIODevice::ReadOnly))
{
QByteArray array;
array = file->readLine();
qDebug() << array;
}
file->close();
QDebug always gets an empty string.#
QFile *file = new QFile("gh.txt");
// ^^^^^^^^
The issue is that you are trying to open a file in your current working directory.
You should use this code to fix it:
QFile file(QCoreApplication::applicationDirPath() + "gh.txt");
Also, I do not see the point in allocating the QFile
instance on the heap. You should use stack object here as per the above line.
Actually, your code will even leak the memory explicit deletion which is pointless if you use stack objects.
Moreover, there is no need to call close explicitly. This is C++, and you have got RAII. It will be called automatically by the destructor of the QFile
class.
Also, despite that you are writing open succeeded, it very likely did not. You should always prepare for proper error reporting when it is not successful by using the file.errorString()
method.
So, taking all that into account, your code would be like this:
QFile file(QCoreApplication::applicationDirPath() + "gh.txt");
if (!file.open(QIODevice::ReadOnly))
qDebug() << "Failed to open file:" << file.fileName() << "Error:" << file.errorString();
else
qDebug() << file->readLine();
It is also possible that your file is not next to the executable in which case move it there.
QFile does support relative paths, but it is not a good idea to use it because it can be really relative with different installation which could potentially break the application for others.