As an example, I want to write out some string value, str
, to a file, "yy"
, as it changes through each iteration of a loop. Below is how I'm currently implementing it:
NSOutputStream *oStream = [[NSOutputStream alloc] initToFileAtPath:@"yy" append:NO];
[oStream open];
while ( ... )
{
NSString *str = /* has already been set up */
NSData *strData = [str dataUsingEncoding:NSUTF8StringEncoding];
[oStream write:r(uint8_t *)[strData bytes] maxLength:[strData length]];
...
}
[oStream close];
Ignoring the UTF-8 encoding, which I do require, is this how NSString
s are typically written to a file? That is, by first converting to an NSData
object, then using bytes
and casting the result to uint8_t
for NSOutputStream
's write
?
Are there alternatives that are used more often?
EDIT: Multiple NSString
s need to be appended to the same file, hence the loop above.
(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.
Having stored the contents of a file in an NSData object, that data may subsequently be written out to a new file using the createFileAtPath method: databuffer = [filemgr contentsAtPath: @"/tmp/myfile. txt" ]; [filemgr createFileAtPath: @"/tmp/newfile. txt" contents: databuffer attributes: nil];
FILE *libFile = fopen("/Users/pineapple/Desktop/finalproj/test242. txt","r"); char wah[200]; fgets(wah, 200, libFile); printf("%s test\n", wah);
ctshryock's solution is a bit different than yours, since you're appending as you go, and ctshyrock's write a single file all at once (overwriting the previous version). For a long-running process, these are going to be radically different.
If you do want to write as you go, I typically use NSFileHandle
here rather than NSOutputStream
. It's just a little bit easier to use in my opinion.
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:aPath];
while ( ... )
{
NSString *str = /* has already been set up */
[fileHandle writeData:[str dataUsingEncoding:NSUTF8StringEncoding]];
}
[fileHandle closeFile];
Note that fileHandle
will automatically close when it is dealloced, but I like to go ahead and close it explicitly when I'm done with it.
I typically use NSString's methods writeToFile:atomically:encoding:error:
or writeToURL:atomically:encoding:error:
for writing to file.
See the String Programming Guide for Cocoa for more info
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