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:<
It can happen that the cause is not that you don't find the right directory. For example, you can read from the file (even without absolute path) but it seems you cannot write into it.
In that case, it might be that you program exits before the writing can be finished.
If your program uses an event loop (like with a GUI application, e.g. QMainWindow
) it's not a problem. However, if your program exits immediately after writing to the file, you should flush the text stream, closing the file is not always enough (and it's unnecessary, as it is closed in the destructor).
stream << "something" << endl;
stream.flush();
This guarantees that the changes are committed to the file before the program continues from this instruction.
The problem seems to be that the QFile is destructed before the QTextStream. So, even if the stream is flushed in the QTextStream destructor, it's too late, as the file is already closed.