iOS 實現文件的拷貝

y37f 10年前發布 | 3K 次閱讀 Objective-C IOS

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

}

</pre>

 本文由用戶 y37f 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!