/*
* 复制一个大型文件,为了节约内存,每次只读取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;
}