1 #import "ViewController.h" 2 3 @interface ViewController () 4 5 @end 6 7 @implementation ViewController 8 9 - (void)viewDidLoad {10 [super viewDidLoad];11 //由于文件对接器不能创建文件,所以必须借助文件管理器创建文件,12 NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];13 14 NSString *filePath = [documents stringByAppendingPathComponent:@"text.txt"];15 NSString *str = @"123456789abcdedfghij";16 [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];17 NSLog(@"%@",filePath);18 19 //文件对接器,对文件内容进行操作20 21 //读取22 NSFileHandle *readFileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];23 //从文件中得到可用数据24 //NSData *availableData = [readFileHandle availableData];25 //NSLog(@"%@",[[NSString alloc] initWithData:availableData encoding:NSUTF8StringEncoding]);26 27 //从当前节点,读取指定长度的数据,须把前边的availbleData注掉,不然取不到28 NSData *lengthData = [readFileHandle readDataOfLength:10];29 NSLog(@"%@",[[NSString alloc] initWithData:lengthData encoding:NSUTF8StringEncoding]);30 31 //设置节点偏移量32 [readFileHandle seekToFileOffset:0];33 NSData *lengthData2 = [readFileHandle readDataOfLength:5];34 NSLog(@"%@",[[NSString alloc] initWithData:lengthData2 encoding:NSUTF8StringEncoding]);35 36 NSData *lengthData3 = [readFileHandle readDataOfLength:5];37 NSLog(@"%@",[[NSString alloc] initWithData:lengthData3 encoding:NSUTF8StringEncoding]);38 //从当前节点读取到文件末尾39 NSData *endData = [readFileHandle readDataToEndOfFile];40 NSLog(@"%@",[[NSString alloc] initWithData:endData encoding:NSUTF8StringEncoding]);41 42 //关闭文件43 [readFileHandle closeFile];44 //写入数据45 NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];46 47 //设置节点位置48 [writeHandle seekToFileOffset:10];49 //写入50 [writeHandle writeData:lengthData];51 //获取节点偏移量52 NSInteger offset = [writeHandle offsetInFile];53 NSLog(@"%ld",offset);54 55 //将文件长度设置为偏移量56 [writeHandle truncateFileAtOffset:40];57 //关闭文件58 [writeHandle closeFile];59 60 61 }