首页 > 代码库 > 文件句柄NSFileHandle
文件句柄NSFileHandle
//一.读取
//1.以只读方式打开
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:txtPath];
//2.读取所有内容
NSData *allData = http://www.mamicode.com/[fh readDataToEndOfFile];
//转化str
NSString *str = [[NSString alloc]initWithData:allData encoding:NSUTF8StringEncoding];
NSLog(@"--%@",str );
//3.读取指定长度
//(注意:中文占3个字节)
//(注意:会接着上一次继续读取)
NSData *subData = http://www.mamicode.com/[fh readDataOfLength:3];
NSString *str1 = [[NSString alloc]initWithData:subData encoding:NSUTF8StringEncoding];
NSLog(@"--%@--%ld",str1,str1.length);
//4.偏移(定位到某个字节,然后再读)
[fh seekToFileOffset:4];
NSData *offData = http://www.mamicode.com/[fh readDataToEndOfFile];
NSString *str2 = [[NSString alloc]initWithData:offData encoding:NSUTF8StringEncoding];
NSLog(@"--%@--%ld",str2,str2.length);
//5.关闭文件
[fh closeFile];
<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #1e9421 } p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #000000 } p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #3e1e81 } p.p4 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px "PingFang SC"; color: #1e9421 } span.s1 { } span.s2 { font: 18.0px "PingFang SC" } span.s3 { color: #1e9421 } span.s4 { font: 18.0px "PingFang SC"; color: #1e9421 } span.s5 { color: #000000 } span.s6 { color: #6122ae } span.s7 { font: 18.0px Menlo; color: #000000 } span.s8 { font: 18.0px Menlo } span.s9 { color: #c81b13 } span.s10 { color: #3e1e81 }</style>
//二.写入
//只写
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:txtPath];
//读,写
// NSFileHandle *fh1 = [NSFileHandle fileHandleForUpdatingAtPath:txtPath];
//1.设置偏移到最后
[fh seekToEndOfFile];
//.注意:如seek到某个字节:是覆盖后面内容,不是插入
//[fh seekToFileOffset:3];
//2.写入
NSData *data = http://www.mamicode.com/[@"writeToText" dataUsingEncoding:NSUTF8StringEncoding];
[fh writeData:data];
文件句柄NSFileHandle