如何在Qt中创建一个新文件 [英] How to create a new File in Qt

查看:934
本文介绍了如何在Qt中创建一个新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个Qt初学者,只是陷入了这个问题。我正在寻找一个文件SomePath / NewDirectoryA / NewFile.kml(NewFile.kml将是唯一的文件在NewDirectoryA,有这个目录只是为了维护项目中的语义)。

<如果SomePath / NewDirectoryA / NewFile.kml存在,那么我将在我的代码中使用它,如果它不存在,那么我必须创建它。如果这个文件不存在,那么这个目录在SomePath中也不存在。所以,如果只有我必须创建一个文件,我可以使用QFile并打开它在ReadWrite或WriteOnly模式。

但问题是我必须创建文件的目录本身。我用QFile与文件名称SomePath / NewDirectoryA / NewFile.kml尝试,但它没有奏效。请给我一个方法,我可以在一个新的目录(NewDirectorA)在给定的位置(SomePath)创建一个新的文件(NewFile.kml)。

解决方案


bool QFile :: open (OpenMode模式)[virtual]

注意:在WriteOnly或ReadWrite模式下,
(如果相关文件还没有
存在),这个函数将尝试
创建一个新的文件,然后打开它。

Qt的文件创建警告


平台特定问题



文件权限在类Unix系统和
Windows上的处理方式不同。在类Unix系统的不可写目录中,不能创建
文件。在Windows上并不总是这样,对于
实例,我的文档目录通常不可写,但
仍然可以在其中创建文件。



$ b


bool
QDir :: mkdir
(const QString& dirName )const创建一个名为
dirName的子目录。






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


创建目录路径dirPath。

该函数将创建创建
目录所需的所有父
目录。



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

解决方案

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.

这篇关于如何在Qt中创建一个新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆