Objective-C中使用 NSFileHandle处理文件的读写问题

代码:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSArray *pathStr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *plst1 = [pathStr objectAtIndex:0];
    
    NSLog(@"The path is %@", plst1);
    
    NSString *fname = [plst1 stringByAppendingPathComponent:@"longreport.txt"];
    
    NSString *firstStr = @"This is the first line of report.\n";

    NSError *err;
    BOOL success1 = [firstStr writeToFile:fname
                                   atomically:YES
                                     encoding:NSUTF8StringEncoding
                                        error:&err];
    if(success1){
        NSLog(@"The first line is written ok");
    } else {
        NSLog(@"The first line is written wrong, the error is %@", [err localizedDescription]);
    }
    //创建NSFileHandle实例
    //fileHandleForUpdatingAtPath 可读写
    NSFileHandle *handler = [NSFileHandle fileHandleForUpdatingAtPath:fname];
    //将游标设为文件的结尾处
    [handler seekToEndOfFile];
    
    NSString *secStr = @"The second line.\n";
    NSData *secData = [secStr dataUsingEncoding:NSUTF8StringEncoding];
    
    [handler writeData:secData];

    
    [handler closeFile];
    
    NSLog(@"ALl lines had been written done");
    
    

Log:

2018-03-22 00:33:59.133478+0800 TOCPlistb[9452:496809] The path is /Users/demi/Library/Developer/CoreSimulator/Devices/39B68ED5-2ED6-4691-AF8D-7E75D1FE8D5E/data/Containers/Data/Application/7DDC550B-C356-4AE5-98B0-E459A48AAF63/Documents

2018-03-22 00:33:59.134655+0800 TOCPlistb[9452:496809] The first line is written ok

2018-03-22 00:33:59.135215+0800 TOCPlistb[9452:496809] ALl lines had been written done


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值