Writing variables and strings to a text file (

2019-09-10 01:25发布

I was surfing on the Net a lot, but still I haven't found an answer to my question: how to write variables to a .txt file and what's the best way to write NSStrings to .txt files. I've tried using writeToFile method, but if I have two calls of this method, then the text that was written when the first one was called will be overwritten. I want to have a kind of history of what has happened, and values of some variables in my .txt file. How should I do it?

1条回答
可以哭但决不认输i
2楼-- · 2019-09-10 02:09

If you just want to append a string to a .txt file, you could do this:

NSString *string = ...;   // your string
NSString *path = ...;     // path to your .txt file
// Open output file in append mode:
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:path append:YES];
[stream open];
// Make NSData object from string:
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
// Write data to output file:
[stream write:data.bytes maxLength:data.length];
[stream close];
查看更多
登录 后发表回答