//一.读取

//1.以只读方式打开

NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:txtPath];

//2.读取所有内容

NSData *allData = [fh readDataToEndOfFile];

//转化str

NSString *str = [[NSString alloc]initWithData:allData encoding:NSUTF8StringEncoding];

NSLog(@"--%@",str );

//3.读取指定长度

//(注意:中文占3个字节)

//(注意:会接着上一次继续读取)

NSData *subData = [fh readDataOfLength:3];

NSString *str1 = [[NSString alloc]initWithData:subData encoding:NSUTF8StringEncoding];

NSLog(@"--%@--%ld",str1,str1.length);

//4.偏移(定位到某个字节,然后再读)

[fh seekToFileOffset:4];

NSData *offData = [fh readDataToEndOfFile];

NSString *str2 = [[NSString alloc]initWithData:offData encoding:NSUTF8StringEncoding];

NSLog(@"--%@--%ld",str2,str2.length);

//5.关闭文件

[fh closeFile];

//二.写入

//只写

NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:txtPath];

//读,写

//    NSFileHandle *fh1 = [NSFileHandle fileHandleForUpdatingAtPath:txtPath];

//1.设置偏移到最后

[fh seekToEndOfFile];

//.注意:如seek到某个字节:是覆盖后面内容,不是插入

//[fh seekToFileOffset:3];

//2.写入

NSData *data = [@"writeToText" dataUsingEncoding:NSUTF8StringEncoding];

[fh writeData:data];

05-11 17:02