[Resolved]Unable to read my txt file.
-
Hi,
I try to code a simple application that reads a txt file. The problem is that when I run it from QT Creator, it doesn't find the txt file. However, when I run the application directly from its directory, the file is correctly opened. So I suppose that the code is right so I don't understand where is the problem. Thanks for helping me.
the code is :
@#include <QApplication>
#include <QFile>
#include <QString>
#include <QTextEdit>int main(int argc, char **argv)
{
QApplication a(argc, argv);
QTextEdit zoneTexte;
zoneTexte.setGeometry(100,100,400,200);
zoneTexte.setReadOnly(true);QString texte; QFile fichier("test.txt"); if(fichier.open(QIODevice::ReadOnly | QIODevice::Text)) { texte = fichier.readAll(); fichier.close(); } else texte = "Impossible d'ouvrir le fichier !"; zoneTexte.setText(texte); zoneTexte.show(); return a.exec();
}
@ -
Welcome to this forum.
You probably have to set the working directory in qt ctreator. Under "projects" you can find the "Run settings", where you can set the working directory. In your case it is the directory with your file. An alternative would be to include the complete absolute path of your file. E.g. for windows
@
QFile fichier("C:/data/test.txt");
@ -
So you have a app.exe and test.txt in the same dir, right?
You can try this code to see current application dir:
@qDebug()<<QApplication::applicationDirPath();@
and compare it with your actual application directory. -
Have you tried to set the working directory in Projects->Run Settings?
-
Thank you,
I try the both alternatives but it doesn't work so I choose "working directory" by default.
And by running the qDebug instruction, I get the correct path.The solution by including the full path will certainely work...but it will constrain the application.
I've tried to find how QT Creator run the .exe application and if there was any options regarding the way it is run but no result.