I am trying to write into a file and if the file doesn't exist create it. I have searched on the internet and nothing worked for me.
My code looks currently like this:
QString filename="Data.txt"; QFile file( filename ); if ( file.open(QIODevice::ReadWrite) ) { QTextStream stream( &file ); stream << "something" << endl; }
If I create a text file called Data in the directory, it remains empty. If I don't create anything it doesn't create the file either. I don't know what to do with this, this isn't the first way in which I tried to create/write into a file and none of the ways worked.
Thanks for your answers.
Your current working folder is set by Qt Creator. Go to Projects >> Your selected build >> Press the 'Run' button (next to 'Build) and you will see what it is on this page which of course you can change as well. Show activity on this post. It can happen that the cause is not that you don't find the right directory.
To write text, we can use operator<<(), which is overloaded to take a QTextStream on the left and various data types (including QString) on the right. In the following code, we open a new file with the given name and write a text into the file. Then, we read in the file back and print the content to our console.
The only way I was able to create a folder was right-click on the 'MyApp' root folder in QtCreator, select 'Add New' and choose to add a new QML file. At that point, it brings up a file Browse dialog and you can navigate to the folder you created and drop the file in there.
That is weird, everything looks fine, are you sure it does not work for you? Because this main
surely works for me, so I would look somewhere else for the source of your problem.
#include <QFile> #include <QTextStream> int main() { QString filename = "Data.txt"; QFile file(filename); if (file.open(QIODevice::ReadWrite)) { QTextStream stream(&file); stream << "something" << endl; } }
The code you provided is also almost the same as the one provided in detailed description of QTextStream so I am pretty sure, that the problem is elsewhere :)
Also note, that the file is not called Data
but Data.txt
and should be created/located in the directory from which the program was run (not necessarily the one where the executable is located).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With