首页 > 代码库 > NSFileHandle的用法

NSFileHandle的用法

////  FileInfo.m//  MemoryManage////  Created by macos on 14-8-10.//  Copyright (c) 2014年 macos. All rights reserved.//#import "FileDemo.h"@implementation FileDemo-(id) init{    if (self = [super init]) {        NSFileManager *mgr =[NSFileManager defaultManager];        NSString *path = [NSHomeDirectory() stringByAppendingString:@"/mac.text"];        NSLog(@"%@",path);        NSString *data=http://www.mamicode.com/@"abcdefghijklmn";        [mgr createFileAtPath:path contents:[data dataUsingEncoding:NSUTF8StringEncoding] attributes:Nil];        //NSFileHandle无法创建文件        NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:path];        NSLog(@"%@",[[NSString alloc] initWithData:[file readDataToEndOfFile] encoding:NSUTF8StringEncoding]);        [file seekToFileOffset:0];        NSLog(@"length:%lu",[file availableData].length);        [file seekToEndOfFile];        NSDateFormatter *datefmt = [[NSDateFormatter alloc] init];        [datefmt setDateFormat:@" yyyy-MM-dd HH:mm:ss"];        NSString *ndata=http://www.mamicode.com/[datefmt stringFromDate:[NSDate date]];        [file writeData:[ndata dataUsingEncoding:NSUTF8StringEncoding]];        [file seekToFileOffset:0];        [self copyFileToPath:file ToPath:[NSHomeDirectory() stringByAppendingString:@"/mac.bak.text"]];                [file closeFile];    }    return self;}-(BOOL) copyFileToPath:(NSFileHandle *)srcFile ToPath:(NSString *)path{    NSFileManager *fm = [NSFileManager defaultManager];    //创建新的空文件    NSFileHandle *newFile = [fm createFileAtPath:path contents:[srcFile readDataToEndOfFile ] attributes:nil];    [newFile closeFile];    return true;}@end