代码:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *pathStr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *plst1 = [pathStr objectAtIndex:0];
NSLog(@"The path is %@", plst1);
NSString *fname = [plst1 stringByAppendingPathComponent:@"longreport.txt"];
NSString *firstStr = @"This is the first line of report.\n";
NSError *err;
BOOL success1 = [firstStr writeToFile:fname
atomically:YES
encoding:NSUTF8StringEncoding
error:&err];
if(success1){
NSLog(@"The first line is written ok");
} else {
NSLog(@"The first line is written wrong, the error is %@", [err localizedDescription]);
}
//创建NSFileHandle实例
//fileHandleForUpdatingAtPath 可读写
NSFileHandle *handler = [NSFileHandle fileHandleForUpdatingAtPath:fname];
//将游标设为文件的结尾处
[handler seekToEndOfFile];
NSString *secStr = @"The second line.\n";
NSData *secData = [secStr dataUsingEncoding:NSUTF8StringEncoding];
[handler writeData:secData];
[handler closeFile];
NSLog(@"ALl lines had been written done");
Log:
2018-03-22 00:33:59.133478+0800 TOCPlistb[9452:496809] The path is /Users/demi/Library/Developer/CoreSimulator/Devices/39B68ED5-2ED6-4691-AF8D-7E75D1FE8D5E/data/Containers/Data/Application/7DDC550B-C356-4AE5-98B0-E459A48AAF63/Documents
2018-03-22 00:33:59.134655+0800 TOCPlistb[9452:496809] The first line is written ok
2018-03-22 00:33:59.135215+0800 TOCPlistb[9452:496809] ALl lines had been written done