File
และแล้วก็เกือบมาถึง โค้งสุดท้ายแล้ว สำหรับ objective-c programming นั่นก็คือเรื่อง file นั่นเอง
สำหรับ file นั้นเราสามารถที่จะใช้ class ที่ชื่อว่า NSFileManger เพื่อทำการ copy , rename ได้และอื่นๆ การใช้งานก็เพียงแค่ทำการประกาศตัวแปร แบบ NFFileManager ขึ้นมา และทำการ alloc ด้วย defaultManager ดังตัวอย่างข้างล่าง
int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSFileManager *fileMgr; fileMgr = [NSFileManager defaultManager]; // File exists. if([fileMgr fileExistsAtPath:@"test.txt"] == YES) printf("Found filen"); // Copy file if([fileMgr copyPath:@"test.txt" toPath:@"hello.txt" handler:nil] == YES) printf("Copy file completedn"); // Rename file if( [fileMgr movePath:@"hello.txt" toPath:@"ok.txt" handler:nil] == YES) printf("Rename file completedn"); // Compare file if( [fileMgr contentsEqualAtPath:@"ok.txt" andPath:@"test.txt"] == YES) printf("File are equaln"); // Delete file if ( [fileMgr removeFileAtPath:@"ok.txt" handler:nil] == YES) printf("File deletedn"); // Get file size NSDictionary *attr; attr = [fileMgr fileAttributesAtPath:@"test.txt" traverseLink:NO]; if (attr != nil) { printf("File size: %d bytes", [[ attr objectForKey:NSFileSize] intValue] ); } [pool drain]; return 0; }
จากตัวอย่างข้างบน methode ที่เบื้องต้นเกียวกับ file ก็คือ
- fileExistsAtPath
- copyPath:toPath: toPath: handler:
- movePath:toPath: toPath: handler:
- contentsEqualAtPath: andPath:
- removeFileAtPath: handler:
- fileAttributesAtPath
ถ้าดูจากตัวอย่างข้างบนก็จะตรงตัวอยู่แล้วว่าแต่ละอย่างทำอะไร แต่จะมีแปลกหน่อยตรงที่ fileAttributesAtPath มันจะ ส่ง NSDictionary กลับมาให้ แล้วเราค่อย เรียก NSFileSize เพื่อหาค่าขนาดของไฟล์อีกที ( ถ้ายังไม่เข้าใจ NSDictionary กลับไปดูในบทก่อนๆได้ )
Directory
NSFileManager ยังมีฟังชั่นเกี่ยวกับ Directory ที่คล้ายๆกับ file นั่นก็คือ
- createDirectoryAtPath: attributes:
- movePath: toPath:
- changeCurrentDirectoryPath:
3 methode บ้างบนก็ทำหน้าที่คือ สร้าง , ลบ และ ทำการเปลี่ยน directory ที่กำลังใช้งาน
เพื่อความเข้าใจดู code ตัวอย่างง่ายกัน
NSFileManager *fileMgr = [NSFileManager defaultManager]; // Get Current path printf("Current path: %sn", [[fileMgr currentDirectoryPath] UTF8String]); // Create new directory if([fileMgr createDirectoryAtPath:@"test" attributes:nil] == YES) printf("Directory createdn"); // Rename dictory if([fileMgr movePath:@"test" toPath:@"simple" handler:nil] == YES) printf("Directory renamedn"); // change working directory if([fileMgr changeCurrentDirectoryPath:@"simple"] == YES) { printf("Now current path is: %sn", [[fileMgr currentDirectoryPath] UTF8String]); }
จะเห็นว่าการใช้งานนั้นไม่ได้ยากเลย สำหรับการเขียนข้อมูล และการอ่านข้อมูลไฟล์ คงต่อในครั้งหน้า


