Re: How to write a string to a file
Re: How to write a string to a file
- Subject: Re: How to write a string to a file
- From: Ken Thomases <email@hidden>
- Date: Mon, 18 Aug 2008 22:13:11 -0500
On Aug 18, 2008, at 10:00 PM, David wrote:
I know it sounds like a basic question, but I've looked and it
doesn't seem
as obvious to me as it should.
I want to write out data to a file to describe my tree structure.
I'd like to have a method which appends a string to the end of a
text file.
I don't really want to store everything in memory and write out one
big
string because it might get quite large.
How are you supposed to do this in Cocoa? Why isn't it more obvious?
I've looked in NSString, NSData, NSFileHandle, NSOutputStream, but
I don't
see a simple way to append a string to a file. Can it really be
this hard?
NSString doesn't have a method to append to a file, nor a stream, nor
NSData.
And the other classes don't have a method to accept a string.
Any attempt to store a string raises the question of how the string
should be represented. That is, what encoding it should be written in.
That question is not something the framework can decide on its own.
You need to decide that. Once you do, you can obtain an NSData from
an NSString with your desired encoding (-[NSString dataUsingEncoding:]).
Once you've got an NSData, you can append it to a file using
NSFileHandle. You need to seek to the end of the file before
writing. Use something like:
[fh seekToEndOfFile];
[fh writeData:[myString dataUsingEncoding: NSUTF8StringEncoding]];
Cheers,
Ken
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden