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

后端 未结 2 1560
鱼传尺愫
鱼传尺愫 2021-01-07 17:58

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 fi

相关标签:
2条回答
  • 2021-01-07 18:41

    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
    
    0 讨论(0)
  • 2021-01-07 19:00

    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.

    0 讨论(0)
提交回复
热议问题