Objective-C:随机的读取文件中的内容

 可以通过改变当前文件的偏移量来实现文件的读取

-offsetInFile获取文件当前的位移量
-seekToFileOffset:(NSUInteger)length设置文件当前的位移量
-readDataOfLength:(NSUInteger)length随机读取文件内容的字节数
-seekToEndOfFile将文件跳到结尾
 1 //
 2 //  main.m
 3 //  04-NSFileHandle随机读取
 4 //
 5 //  Created by ma c on 15/8/24.
 6 //  Copyright (c) 2015年. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 int main(int argc, const char * argv[])
12 {
13     @autoreleasepool
14     {
15         //创建文件
16         NSString *str = @"this is a test\nhello world\nHow are you?";
17         NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
18         
19         NSFileManager *fm = [NSFileManager defaultManager];
20         
21         if(![fm createFileAtPath:@"1.txt" contents:data attributes:nil])
22         {
23             NSLog(@"创建文件失败");
24             return -1;
25         }
26         
27         //随机读取文件
28         NSFileHandle *in = [NSFileHandle fileHandleForReadingAtPath:@"1.txt"];
29         if(in)
30         {
31             //读取部分内容
32             NSData *content = [in readDataOfLength:5];
33             NSLog(@"%@",[[NSString alloc]initWithData:content encoding:NSUTF8StringEncoding]);
34             
35             //查看当前文件偏移量
36             NSUInteger offset = [in offsetInFile];
37             NSLog(@"offset:%lu",offset);
38             
39             //设置文件偏移
40             [in seekToFileOffset:10];
41             
42             //再读10个字节
43             content = [in readDataOfLength:10];
44             NSLog(@"%@",[[NSString alloc]initWithData:content encoding:NSUTF8StringEncoding]);
45             
46             //直接跳到文件尾
47             [in seekToEndOfFile];
48             
49             //截取文件或者扩展文件(超出了文件长度)
50             //[in truncateFileAtOffset:10];
51         }
52         [in closeFile];
53     }
54     return 0;
55 }

 

posted @ 2015-08-24 21:13  XYQ全哥  阅读(481)  评论(0编辑  收藏  举报