iOS 实现文件的拷贝

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

 #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;

    }