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

75,604

Solution 1

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.

Solution 2

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

QString path("SomePath/NewDirectoryA/");
QDir dir; // Initialize to the desired dir if 'path' is relative
          // By default the program's working directory "." is used.

// We create the directory if needed
if (!dir.exists(path))
    dir.mkpath(path); // You can check the success if needed

QFile file(path + "NewFile.kml");
file.open(QIODevice::WriteOnly); // Or QIODevice::ReadWrite
Share:
75,604
GG.
Author by

GG.

Undergraduate in computer science from ITBHU.

Updated on March 27, 2020

Comments

  • GG.
    GG. over 4 years

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