Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating/writing into a new file in Qt

Tags:

c++

qt

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.

like image 802
Tom83B Avatar asked Feb 06 '11 21:02

Tom83B


People also ask

How do you create a file and write it in Qt?

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.

How do you write data to a file in Qt?

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.

How do I create a folder in Qt?

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.


1 Answers

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).

like image 65
Palmik Avatar answered Oct 07 '22 19:10

Palmik