NSFileHandle & NSFileManager 文件复制例程

本文介绍了一种在Objective-C中分段读取并复制大型文件的方法,以减少内存占用。通过NSFileHandle逐次读取500字节的数据,并将其写入目标文件,直至完成整个文件的复制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*

 * 复制一个大型文件,为了节约内存,每次只读取500字节。

 */


#import <Foundation/Foundation.h>


int main(int argc, const char * argv[])

{


    @autoreleasepool {

        

        // 获取当前用户 路径 /Users/xxh

        NSString *homePath = NSHomeDirectory();

        // 源文件

        NSString *srcPath = [homePath stringByAppendingPathComponent:@"Desktop/Cocos2D_Projects_v2.0.0.zip"];

        // 目标文件

        NSString *tagetPath = [homePath stringByAppendingPathComponent:@"Desktop/Cocos2D_Projects_v2.0.0_back.zip"];

        NSLog(@"targetPaht : %@", tagetPath);

        // 创建文件管理对象

        NSFileManager *fileManager = [NSFileManager defaultManager];

        

        // 新建文件

        BOOL success = [fileManager createFileAtPath:tagetPath contents:nil attributes:nil];

        if (success) {

            NSLog(@"create success!");

        }

        

        // 文件读操作对象

        NSFileHandle *inFileHandle = [NSFileHandle fileHandleForReadingAtPath:srcPath];

        // 文件写操作对象

        NSFileHandle *outFileHandle = [NSFileHandle fileHandleForWritingAtPath:tagetPath];

        

        /*

         * 注意:当获取文件长度时

         * 此方法已经把整个文件读取到内存中,因此就没必要在分段读取数据到内存。

        NSData *data = [inFileHandle availableData];

        NSInteger fileSize = data.length;

        */

        

        // 通过文件属性获取文件长度

        NSDictionary *fileAttribute = [fileManager attributesOfFileSystemForPath:srcPath error:nil];

        NSNumber *fileSizeNum = [fileAttribute objectForKey:NSFileSize];

        NSInteger fileSize = [fileSizeNum longValue];

        

        BOOL isEnd = YES;

        NSInteger readSize = 0; // 读取文件的字节数

        while (isEnd) {

            NSInteger subLength = fileSize - readSize;

            NSData *data = nil;

            if (subLength < 500) {

                isEnd = NO;

                data = [inFileHandle readDataToEndOfFile];

            }

            else

            {

                data = [inFileHandle readDataOfLength:500];

                readSize += 500;

                [inFileHandle seekToFileOffset:500];

            }

            [outFileHandle writeData:data];

        }

        [inFileHandle closeFile];

        [outFileHandle closeFile];

    }

    return 0;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值