I've found this way of creating a directory if it does not exist. But it looks a bit wonky and I am afraid that this can go wrong in 1 of 1000 attempts.
if(![[NSFileManager defaultManager] fileExistsAtPath:bundlePath]) { [[NSFileManager defaultManager] createDirectoryAtPath:bundlePath withIntermediateDirectories:YES attributes:nil error:NULL]; }
There is only this awkward method fileExistsAtPath which also looks for files and not only directories. But for me, the dangerous thing is: What if this goes wrong? What shall I do? What is best practice to guarantee that the directory is created, and only created when it does not exist?
I know file system operations are never safe. Device could loose battery power suddenly just in the moment where it began shoveling the bits from A to B. Or it can stumble upon a bad bit and hang for a second. Maybe in some seldom cases it returns YES even if there is no directory. Simply put: I don't trust file system operations.
How can I make this absolutely safe?
When you want to create a directory in a path that does not exist then an error message also display to inform the user. If you want to create the directory in any non-exist path or omit the default error message then you have to use '-p' option with 'mkdir' command.
You can use the Java File class to create directories if they don't already exists. The File class contains the method mkdir() and mkdirs() for that purpose. The mkdir() method creates a single directory if it does not already exist.
To create a directory if not exist in Python, check if it already exists using the os. path. exists() method, and then you can create it using the os. makedirs() method.
You can actually skip the if
, even though Apple's docs say that the directory must not exist, that is only true if you are passing withIntermediateDirectories:NO
That puts it down to one call. The next step is to capture any errors:
NSError * error = nil; [[NSFileManager defaultManager] createDirectoryAtPath:bundlePath withIntermediateDirectories:YES attributes:nil error:&error]; if (error != nil) { NSLog(@"error creating directory: %@", error); //.. }
This will not result in an error if the directory already exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With