Opening txt files in qt c++ and writing to it.
-
Hello everyone,
I'm having problems writing to files in qt. I have tried using QFile and using fstream but both seem to have problems. The problem is that although I think the code is right, the file isn't being written to at the location of the project, rather it is being written in the build directory. I tried changing the build directory to the location of the active project but that too doesn't seem to do anything.
Any help is greatly appreciated.
Thanks in advance -
Hi, this is the code:
QString url; QFile file("urlfile.txt"); file.open(QIODevice::ReadOnly | QIODevice::WriteOnly | QIODevice::Text); QTextStream txtStream(&file); txtStream << "Hello"; qDebug() << "OK"; file.close();
I want it to create the txt file in the same location as the directory that the project is saved in, because afterwards I call a python exe file, which needs to open the file. Hope you understand thanks
-
Hi, this is the code:
QString url; QFile file("urlfile.txt"); file.open(QIODevice::ReadOnly | QIODevice::WriteOnly | QIODevice::Text); QTextStream txtStream(&file); txtStream << "Hello"; qDebug() << "OK"; file.close();
I want it to create the txt file in the same location as the directory that the project is saved in, because afterwards I call a python exe file, which needs to open the file. Hope you understand thanks
@Alfie-Anil Why ReadOnly | WriteOnly? Use just one please (I guess in your case WriteOnly).
-
Hi, this is the code:
QString url; QFile file("urlfile.txt"); file.open(QIODevice::ReadOnly | QIODevice::WriteOnly | QIODevice::Text); QTextStream txtStream(&file); txtStream << "Hello"; qDebug() << "OK"; file.close();
I want it to create the txt file in the same location as the directory that the project is saved in, because afterwards I call a python exe file, which needs to open the file. Hope you understand thanks
@Alfie-Anil said in Opening txt files in qt c++ and writing to it.:
QFile file("urlfile.txt");
This file will be relative to whatever the current directory happens to be in your application at the time the line is executed. Which may or may not be correct.
Safer would be to use an absolute path.
the same location as the directory that the project is saved in
I don't know what "the directory that the project is saved in" is. There will not be any Qt methods to retrieve such a thing. There will be for, say, where the executable is being run from.
Writing to such a location at runtime is not a good idea anyway. Look through https://doc.qt.io/qt-5/qstandardpaths.html#StandardLocation-enum to find a suitable one for where you want to save the file, and use that to build the absolute path.