標籤:
//
// 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:SRCPATHerror:&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 = [NSFileHandlefileHandleForReadingAtPath: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;
}
iOS 實現檔案的拷貝