iOS 实现文件的拷贝

//

//  main.m

//  filecopy

//

//  Created by GuoYule on 15/2/19.

//  Copyright (c) 2015 GuoYule. All rights reserved.

//


#import <Foundation/Foundation.h>

//实现文件的拷贝

#define SRCPATH @"/Users/guoyule/Desktop/emailreceipt_20150214R3887454299_new.pdf"

#define DSTPATH @"/Users/guoyule/Desktop/emailreceipt_20150214R3887454299_new1.pdf"

#define PERROR (error) if(error){NSLog(@"%@",error);exit(-1);}

#define BUFF 100

//缓冲区大小

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

    @autoreleasepool {


        //所谓文件拷贝 就是从原文件里读往目的文件里写

        //首先创建文件

        NSFileManager * fm =[NSFileManager defaultManager];

        NSError * error = nil;

        //获取源文件的属性

        NSDictionary *attributes = [fm attributesOfItemAtPath:SRCPATH error:&error];

//        PERROR(error);

        if(error){NSLog(@"%@",error);exit(-1);};

        //创建新文件

       BOOL ret = [fm createFileAtPath:DSTPATH contents:nil attributes:attributes];

        if (!ret) {

            perror("createFile");

            exit(-1);

        }

        //打开文件句柄

           NSFileHandle * srcFh = [NSFileHandle fileHandleForReadingAtPath:SRCPATH];

        NSFileHandle * dstFh = [NSFileHandle fileHandleForWritingAtPath:DSTPATH];

        //不要一口气就将源文件读入内存

        //首先要获取源文件大小

//        size_t size = [[attributes objectForKey:@"NSFileSize"] integerValue];

        unsigned long long size = [attributes fileSize];

        //这是一个方法,只有当字典中装文件属性才有效 实际上是一个类别

        /*

         @interface NSDictionary (NSFileAttributes)

         

         - (unsigned long long)fileSize;

         - (NSDate *)fileModificationDate;

         - (NSString *)fileType;

         - (NSUInteger)filePosixPermissions;

         - (NSString *)fileOwnerAccountName;

         - (NSString *)fileGroupOwnerAccountName;

         - (NSInteger)fileSystemNumber;

         - (NSUInteger)fileSystemFileNumber;

         - (BOOL)fileExtensionHidden;

         - (OSType)fileHFSCreatorCode;

         - (OSType)fileHFSTypeCode;

         - (BOOL)fileIsImmutable;

         - (BOOL)fileIsAppendOnly;

         - (NSDate *)fileCreationDate;

         - (NSNumber *)fileOwnerAccountID;

         - (NSNumber *)fileGroupOwnerAccountID;

         @end


         */

        while (size) {

            NSData * data =  nil;

            if (size <= BUFF) {

                data = [srcFh readDataToEndOfFile];

                size  = 0;

            }else{

                //先读100个字节

                data = [srcFh readDataOfLength:BUFF];

                size -= BUFF;

            }

            [dstFh writeData:data];

        }

    }

    return 0;

    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值