Search code examples
qtfileqfile

How to create a new File with full path in Qt?


I am a Qt beginner and just got stuck with the problem. I am looking for a file SomePath/NewDirectoryA/NewFile.kml (NewFile.kml will be the only file in NewDirectoryA, having this directory just to maintain semantics in the project).

If SomePath/NewDirectoryA/NewFile.kml exists then I will use it in my code and if it doesn't exist then I have to create it. If this File doesn't exist then this directory also doesn't exist in SomePath. So If only I have to create a file I can use QFile and open it in ReadWrite or WriteOnly mode.

But the problem is I have to create the file with the directory itself.
I tried with QFile with file name SomePath/NewDirectoryA/NewFile.kml but it didn't worked.

Please suggest me a way in which I can create a new file (NewFile.kml) in a new directory (NewDirectorA) at a given location (SomePath).


Solution

  • bool QFile::open ( OpenMode mode ) [virtual]

    [...]

    Note: In WriteOnly or ReadWrite mode, if the relevant file does not already exist, this function will try to create a new file before opening it.

    Qt's caveat for file creation

    Platform Specific Issues

    File permissions are handled differently on Unix-like systems and Windows. In a non writable directory on Unix-like systems, files cannot be created. This is not always the case on Windows, where, for instance, the 'My Documents' directory usually is not writable, but it is still possible to create files in it.

    Directories are created with

    bool QDir::mkdir ( const QString & dirName ) const

    Creates a sub-directory called dirName.

    and

    bool QDir::mkpath ( const QString & dirPath ) const

    Creates the directory path dirPath.

    The function will create all parent directories necessary to create the directory.