13

I am looking to create an empty file so I can open it for writing using NSFileHandle, is this the correct way or am I missing some better method?

success = [fileManager createFileAtPath:dataFile_OUT contents:nil attributes:nil];

outFile = [NSFileHandle fileHandleForWritingAtPath:dataFile_OUT];

gary

fuzzygoat
  • 26,573
  • 48
  • 165
  • 294
  • I know its only simple, but I just wanted to check. – fuzzygoat Dec 10 '09 at 11:01
  • [see this post][1] [1]: http://stackoverflow.com/questions/7011070/how-to-programmatically-create-an-empty-m4a-file-of-a-certain-length-under-ios/10159799#10159799 – user698333 Apr 15 '12 at 05:35

1 Answers1

20

I don't see anything wrong with what you've got... sounds logical if you are planning on writing to the file in a stream.

If the size and availability of your data is such that you don't need to maintain an open channel to which you can stream data (which I imagine is not your case since you explicitly specified needing to create an empty file), you could eliminate the second line:

NSString *content = @"Put this in a file please.";
NSData *fileContents = [content dataUsingEncoding:NSUTF8StringEncoding];
[[NSFileManager defaultManager] createFileAtPath:@"/Some/Path/foo.txt"
                                contents:fileContents
                                attributes:nil];
Jarret Hardie
  • 95,172
  • 10
  • 132
  • 126
  • How to handle if I want to create a file and write the streaming binary data into it? At that time I will not have any NSString or NSData in advance to create a file. – Satyam Sep 28 '15 at 01:06