NSFileManager处理目录的一些方法

来源:互联网 发布:淘宝浏览器插件 编辑:程序博客网 时间:2024/05/29 03:20

下面总结了NSFileManager处理目录的一些方法,大多数方法和用于普通文件的方法相同,如下所示:

NSFileManager处理目录的方法

下面是代码示例。出于获得信息的目的,首先获得当前的目录路径,然后,在当前的目录中创建一个名为testdir的新目录(文件夹)。然后使用movePath:toPath:handler:方法将新目录testdir重命名为newdir。另外,这个方法还可以用来将整个目录结构(这就意味着包括目录中的内容)从文件系统的一个位置移动到另一个位置。

[cpp] view plaincopy
  1. #import <Foundation/Foundation.h>  
  2.   
  3. int main(int argc, const char * argv[])  
  4. {  
  5.   
  6.     @autoreleasepool {  
  7.           
  8.          
  9.         NSString *dirName = @"testdir";  
  10.         NSString *path;  
  11.         NSFileManager *fm;  
  12.           
  13.         fm = [NSFileManager defaultManager];  
  14.           
  15.         //获取当前目录(directory)既 文件夹  
  16.         path = [fm currentDirectoryPath];  
  17.         NSLog(@"Current directory path is: %@",path);  
  18.           
  19.         //创建一个新的目录  
  20.         if([fm createDirectoryAtPath:dirName attributes:nil] == NO)  
  21.         {  
  22.             NSLog(@"Couldn't create directory!");  
  23.             return 1;  
  24.         }  
  25.           
  26.         //重命名这个新创建的目录  
  27.         if([fm movePath:dirName toPath:@"newdir" handler:nil] == NO)  
  28.         {  
  29.             NSLog(@"Directory rename faild!");  
  30.             return 2;  
  31.         }  
  32.           
  33.         //改变目录到这个新的目录中  
  34.         if([fm changeCurrentDirectoryPath:@"newdir"] == NO)  
  35.         {  
  36.             NSLog(@"Change directory failed!");  
  37.             return 3;  
  38.         }  
  39.           
  40.         //重新获取当前的工作目录  
  41.         path = [fm currentDirectoryPath];  
  42.         NSLog(@"Current directory path is: %@", path);  
  43.           
  44.         NSLog(@"All operations were successful!");  
  45.     }  
  46.     return 0;  
  47. }  


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


0 0
原创粉丝点击