Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating file with directories using QFile

Tags:

qt

I wonder if it's possible to create file with its directories at one blow. For example I want to create file scripts/myFile.txt.

I have written such code:

QFile _file( path );
QDir _dir;

// check if "scripts" folder exists
int _dirExists = _dir.exists( "scripts" );
// if not, create it
if( !_dirExists )
    _dir.mkdir( "scripts" );

// open file in write mode (and text mode) 
int _fileOpened = _file.open( QIODevice::WriteOnly | QIODevice::Text );
if( !_fileOpened ) {
// ...

but I had to use QDir class and I don't like how it looks like. I can't understand why the QFile doesn't create necessary directories itself like in most of this kind of frameworks. Or maybe I have missed something?

like image 757
tobi Avatar asked Jul 30 '12 18:07

tobi


People also ask

Does QFile create a file?

AFAIK it is not possible to create the file and the directory directly with QFile . You have to first create the directory ( QDir::mkpath will create the full path) and then the file ( QFile::open ).

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.

How do I write a QString file?

From Qt doc. about QTextStream::operator<<(const QString &string) : Writes the string string to the stream, and returns a reference to the QTextStream. The string is first encoded using the assigned codec (the default codec is QTextCodec::codecForLocale()) before it is written to the stream.

How do I write a Qt file?

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: QFile file("out. txt"); if (! file.


2 Answers

I know its years afterwars, but QDir::mkpath just worked worked for me.

http://qt-project.org/doc/qt-4.8/qdir.html#mkpath

like image 77
rharriso Avatar answered Oct 16 '22 20:10

rharriso


No, I believe you cannot create the file and it's containing directory in one shot.

like image 25
bmanc Avatar answered Oct 16 '22 21:10

bmanc