【语法】NSFileHandle 文件操作柄

本文介绍了如何使用Objective-C中的NSFileHandle类来实现文件内容的读取与写入操作,包括从一个文件读取数据并将其完整地复制到另一个文件中,以及将一个文件的内容追加到另一个文件末尾的过程。

1.

  // 创建读取的文件操作柄
        NSFileHandle *inFile=[NSFileHandle fileHandleForReadingAtPath:@"/Users/haiyefeng/Desktop/text1.txt"];
        if(inFile==nil)
        {
            NSLog(@"打开文件失败!");
            return 1;
        }
        else
        {
            NSLog(@"打开文件成功!");
        }
        
        
        // 读取内容成功后
        
        // 读取数据到内存缓冲区
        NSData *buffer=[inFile readDataToEndOfFile];
        
        // 创建文件testFile2
        NSString *testFile2=@"/Users/haiyefeng/Desktop/text2.txt";
        // 创建了一个文件
        [[NSFileManager defaultManager]createFileAtPath:testFile2 contents:nil attributes:nil];
        
        // 创建写入的文件操作柄
        NSFileHandle *outFile=[NSFileHandle fileHandleForWritingAtPath:testFile2];
        if(outFile==nil)
        {
            NSLog(@"打开文件失败!");
            return 2;
        }
        else{
            NSLog(@"打开文件成功!");
        }
        
        
        // 偏移量为0
        [outFile truncateFileAtOffset:0];
        
        // 将缓冲区内容写入文件操作柄
        [outFile writeData:buffer];
        
        // 将两个文件关闭
        [inFile closeFile];
        [outFile closeFile];
        
        // 打印新文件内容
        NSLog(@"%@",[NSString stringWithContentsOfFile:testFile2 encoding:NSUTF8StringEncoding error:nil]);

 

 

2.

       NSString *file1=@"/Users/haiyefeng/Desktop/text2.txt";
        NSString *file2=@"/Users/haiyefeng/Desktop/text1.txt";
        
        NSFileHandle *inFile=[NSFileHandle fileHandleForReadingAtPath:file2];
        if(inFile==nil)
        {
            NSLog(@"打开文件file_1失败");
            return 1;
        }
   
        
        //将文件file_1的内容读取出来,并且存储到缓冲区mybuffer
        NSData *myBuffer=[inFile readDataToEndOfFile];
        
        //创建写入的文件操作柄
        NSFileHandle *outFile=[NSFileHandle fileHandleForReadingAtPath:file1];
        if(outFile==nil)
        {
            NSLog(@"打开文件file_2失败");
            return 2;
        }
        
        
        // 将文件file_2的操作位置设定为文件的末尾处
        [outFile seekToEndOfFile];
        
        // 将缓冲区myBuffer中的内容写入文件file_2
        [outFile writeData:myBuffer];
        
        // 关闭文件操作柄
        [inFile closeFile];
        [outFile closeFile];
        

 

转载于:https://www.cnblogs.com/madeininfi/p/3638616.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值