16.1.2 使用目录

表16-2总结了NSFileManager提供的用于处理目录的一些方法。其中大多数方法和用于普通文件的方法相同,如表16-1所示。

16.1.2 使用目录 - 图1

代码清单16-3展示了一些使用目录的基本操作。

代码清单16-3


//Some basic directory operations

import<Foundation/NSObject. h>#import<Foundation/NSString.h>

import<Foundation/NSFileManager.h>

import<Foundation/NSAutoreleasePool.h>

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

{

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

NSString*dirName=@“testdir”;

NSString*path;

NSFileManager*fm;

//Need to create an instance of the file manager

fm=[NSFileManager defaultManager];

//Get current directory

path=[fm currentDirectoryPath];

NSLog(@“Current directory path is%@”,path);

//Create a new directory

if([fm createDirectoryAtPath:dirName attributes:nil]==NO){

NSLog(@“Couldnt create directory!”);

return 1;

}

//Rename the new directory

if([fm movePath:dirName toPath:@“newdir”handler:nil]==NO){

NSLog(@“Directory rename failed!”);

return 2;

}

//Change directory into the new directory

if([fm changeCurrentDirectoryPath:@“newdir”]==NO){

NSLog(@“Change directory failed!”);

return 3;

}

//Now get and display current working directory

path=[fm currentDirectoryPath];

NSLog(@“Current directory path is%@”,path);

NSLog(@“All operations were successful!”);

[pool drain];

return 0;

}


代码清单16-3输出


Current directory path is/Users/stevekochan/progs/ch16

Current directory path is/Users/stevekochan/progs/ch16/newdir

All operations were successful!


代码清单16-3很容易理解。出于获得信息的目的,首先获取当前的目录路径,然后,在当前目录中创建一个名为testdir的新目录。然后使用movePath:toPath:handler:方法将新目录testdir重命名为newdir。记住,这个方法还可以用来将整个目录结构(这意味着包括目录的内容)从文件系统的一个位置移动到另一个位置。

重命名新目录之后,程序使用changeCurrentDirectoryPath:方法将这个新目录设置为当前目录。然后,显示当前目录路径,以验证修改是否成功。