2011年5月7日 星期六

Foundation Framework - 檔案存取 CH16-1 NSFileManager

//

// main.m

// CH16-1 NSFileManager

//

// Created by jason on 2011/5/2.

// Copyright 2011 __MyCompanyName__. All rights reserved.


#import

#import

#import

#import

#import


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

{


NSAutoreleasePool * pool=[[NSAutoreleasePool alloc] init];

NSString *fName=@"testfile";

NSFileManager *fm;

NSDictionary *attr;

//Need to Create an instance of file manager

/*傳送 defaultManager 訊息給NSFileManager 物件的每一個檔案的方法

NSFileManage *fm;

...

fm=[NSFileManager defaultManager];

=> 例如要刪除一個檔案abc,要先建立一個NSFileManager的物件 fm, 然後呼叫removeFileAtPath方法

[fm removeFileAtPath:@"abc" handler: nil ];

也可以判斷回測值

if([fm removeFileAtPath:@"abc" handler: nil]==NO){

NSLog(@" 沒成功喔");

return 1;

}

*/

fm=[NSFileManager defaultManager];

//Let's make sure our test file exists first

if ([fm fileExistsAtPath:fName]==NO){

NSLog(@"File doesnot exist!");

return 1;

}


//Now let's make a copy

if([fm copyPath: fName

toPath:@"newfile"

handler: nil]==NO){

NSLog(@"File copy failed!");

return 2;

}

//Let's test to see if the two files are identical

if([fm contentsEqualAtPath:fName

andPath:@"newfile"]==NO){

NSLog(@"Files are not equal!");

return 3;

}

//Now let's rename the copy

if ([fm movePath:@"newfile"

toPath:@"newfile2" //在同一目錄下,移動檔案並更改檔名

handler:nil]==NO){

NSLog(@"File rename failed!");

return 4;

}

//Get the size of newfile2

//newfile2的檔案屬性交給attr (attrNSDictionary的物件型態)

if((attr =[fm fileAttributesAtPath:@"newfile2"

traverseLink:NO])==nil){

NSLog(@"Could't get file attributes!");

return 5;

}

//透過 objectForKey方法取得 檔案大小

// NSFileSize是鍵值名稱 ,定義在NSFileManager.h

NSLog(@"File size is %i bytes", [[attr objectForKey:NSFileSize] unsignedLongValue]);

//And finally, let's delete the original file

if ([fm removeFileAtPath:fName handler:nil]==NO){

NSLog(@"File remove failed!");

return 6;

}

NSLog(@"All operations were successful!");

//Display the contents of the newly-created file

//newfile2stringWithContentOfFile 讀出字串物件,然後以參數形式送給NSLog顯示

NSLog(@"%@",[NSString stringWithContentsOfFile: @"newfile2"

encoding: NSUTF8StringEncoding

error: nil]);

//最後若此城市過程中若有錯誤皆會停止並會傳回非零的數值,可以用來辨識錯誤發生的地方

[pool drain];

return 0;

//return NSApplicationMain(argc, (const char **) argv);

}

沒有留言: