4

I wish my app to write a file in a specified location, and therefore create the appropriate directory if needed. The create dir operation isn't a problem for me, but I need the dir path. I could extract if from the file path, but maybe is there a quick/concise/convenient way of doing the full operation?

I repeat, I'm not searching the basic makedir function, but one which would take the filename of a possibly non-existing file, or a simple qt function to extract the dir path string from the file path string, so I dont' have to write a func for such a basic task.

spacm
  • 190
  • 3
  • 18
  • Have you searched on google? see [this](http://stackoverflow.com/a/2241818/3062311) – sop Sep 24 '15 at 09:28
  • 2
    possible duplicate of [Checking if a folder exists (and creating folders) in Qt, C++](http://stackoverflow.com/questions/2241808/checking-if-a-folder-exists-and-creating-folders-in-qt-c) – Gombat Sep 24 '15 at 09:30
  • I'd suggest the `mkpath()` as suggested in the [secondmost upvoted answer](http://stackoverflow.com/a/11517874/3399252) – Bowdzone Sep 24 '15 at 09:30
  • Thanks, I searched google and docs, but have you really read my question? – spacm Sep 24 '15 at 09:31
  • So, do you have the full filename, from which you want to extract only the dir path without the file name? – SingerOfTheFall Sep 24 '15 at 09:39
  • yes, I have the full filename, something like "c:\toto\photo.jpg", or "/home/toto/photo.jpg", and I 'd like the dir to exist before I try to write my file. – spacm Sep 24 '15 at 09:42

2 Answers2

5

Use the following code:

const QString filePath = "C:/foo/bar/file.ini";
QDir().mkpath(QFileInfo(filePath).absolutePath());

This code will automatically create the path to the specified (nonexistent) file.


QFileInfo::absolutePath() extracts the absolute path to the specified file.

QDir::mkpath() creates the previously extracted path.

Community
  • 1
  • 1
kefir500
  • 4,184
  • 6
  • 42
  • 48
0

If you have a full path to the file and need to extract the folder path, you can do it this way:

QFile file(full_path_to_the_file);
QFileInfo info(file);
QString directoryPath = info.absolutePath();
//now you can check if the dir exists:
if(QDir(directoryPath).exists())
    //do stuff

Depending on what exactly you need, you may prefer to use QFileInfo::canonicalPath() instead of absolutePath

Alternatively, you may also use QFileInfo::absoluteDir:

QFile file(full_path_to_the_file);
QFileInfo info(file);
if(info.absoluteDir().exists())
    //do stuff
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
  • Thanks, I finally use QFileInfo(QFile(path)).absolutePath() to get the dir path and create it if needed. As this is a very current situation, I hoped there would be a dedicated function for this, but this remains light enough. – spacm Sep 24 '15 at 10:03
  • Just for information: Trying with canonicalPath() failed for me (but absolutePath() is fine) – spacm Sep 24 '15 at 11:17