Solved Can't read from file.
-
This is a really stupid question, but for the life of me, I can't figure out how to read one line of text from a .txt file. Everytime, it says in the console "QIODevice::read: device not open". This is my code.
void Widget::printLine(){ QFile myFile(":/conversations.txt"); myFile.open(QIODevice::ReadOnly | QIODevice::Text); QTextStream conversations(&myFile); QString line = conversations.readLine(); ui->textEdit->setText(line); myFile.close(); }
I've tried putting in the whole address (C:/users...) but that doesn't work. I've also tried adding a resource file and adding a prefix, /, then adding the text file to it. And I've also tried putting it in the same directory as the project (where all the .cpp's and stuff are). I'm almost certain that the problem is because it can't open the file, because I've done different tests to make sure of that. Any ideas what is wrong? Thanks in advance.
-
hi
If you use the ":/XX" syntax then the file must be in a qresource file
included in the project.
http://www.bogotobogo.com/Qt/Qt5_Resource_Files.phpHave you check what open returns ?
if(! myFile.open(QFile::ReadOnly | QFile::Text))
{
qDebug() << " Could not open the file for reading";
return;
}a full path to the file "c:/user/xx/conversations.txt" should have worked.
If you try the qresource way again, then make sure to
clean all-qmake-build all to make sure the res is compiled into
exe.Here is small test project that does it (using your code)
https://www.dropbox.com/s/q9nucvmxgqye7f4/readmyfile.zip?dl=0 -
Thanks you so much!! After trying your code and seeing that it was almost exactly the same as mine, I figured that it was probably something wrong with the actually project (I might have messed something up) so I made a new project and put all your and my code into it and it worked! I also tried my code and it worked too. So I must have messed something up that I wasn't supposed to. I wouldn't have ever figured that out if it wasn't for your code. Thanks a lot!