I am trying to open a file for writing into it. The file may not exist.
I found that [NSFileHandle fileHandleForWritingAtPath:filePath]
returns nil if file does not exist.
Having googled, I found code snippets like this
[[NSData data] writeToFile:filePath atomically:YES]
which, I guess, ensures file existance before opening it.
My questions is: is the latter code line recommended way of file creation? It seems strange that NSFileHandle has no routine to create a new file (and only can deal with existing files).
NSFileHandle
might not have a method to create a file, but NSFileManager
has one. Have you looked at that class?
This works fine for me, however note that it will overwrite the same file each time
NSString *cachesFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [cachesFolder stringByAppendingPathComponent:@"testfile"];
[[NSData data] writeToFile:file options:NSDataWritingAtomic error:nil];
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