OC之文件管理复制文件

//
//  main.m
//  NSFIleHandleTask2
//
//  Created by New-World on 13-11-3.
//  Copyright (c) 2013年 Gary. All rights reserved.
//

#import <Foundation/Foundation.h>
#define Max 5000 //每次读取文件的大小
int main(int argc, const char * argv[])
{

    @autoreleasepool {
#pragma mark 创建文件
        NSString *homepath=NSHomeDirectory();

        NSString *targetPath=[homepath stringByAppendingPathComponent:@"Objective-C_Recipes_bak.pdf"];//需要写入的文件的路
        NSFileManager *filemanager=[NSFileManager defaultManager];
        BOOL isSuccess=[filemanager createFileAtPath:targetPath contents:nil attributes:nil];
        if(isSuccess)
        {
            NSLog(@"创建文件成功!");
        }
        
        NSString *scrPath=[homepath stringByAppendingPathComponent:@"Objective-C_Recipes.pdf"];//需要读取的文件的路径
        NSFileHandle *inFile=[NSFileHandle fileHandleForReadingAtPath:scrPath];
        NSFileHandle *outFile=[NSFileHandle fileHandleForWritingAtPath:targetPath];
#pragma mark 获取文件大小
        NSError *error= nil;
        NSDictionary *fileAttr=[filemanager attributesOfItemAtPath:scrPath error:&error];
        if(nil!=error){
            NSString *str=[error localizedDescription];
            NSLog(@"错误:%@",str);
        }
        //获取文件的属性值
        NSNumber *fileSizeNum=[fileAttr objectForKey:NSFileSize];
        NSInteger fileSize=[fileSizeNum longValue];//文件的大小
#pragma mark 写入文件
        
        NSInteger readSize=0;
        BOOL isEnd =YES;
        
        NSAutoreleasePool *p=nil;//定义一个自动释放池
        int n=0;//进行读取计数
        
        while (isEnd) {
            if(n%10==0)//每十次释放一次内存
            {
                [p release];
                p = [[NSAutoreleasePool alloc]init];
            }
            
            
            
            NSInteger subLength=fileSize-readSize;
            NSData *data=nil;
            if (subLength<Max) {
                isEnd =NO;//表示已经到文件结尾,要退出循环
                [inFile readDataToEndOfFile];//读取到文件末尾
            }
            else
            {
                data=[inFile readDataOfLength:Max];
                
                readSize+=Max;
                [inFile seekToFileOffset:readSize];//设置文件偏移量
            }
            [outFile writeData:data];//向新创建的文件写入数据
            n++;
        }
        NSLog(@"文件复制成功!");
        [inFile closeFile];
        [outFile closeFile];//关闭文件流
        
        
        
        
        
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值