管理文件和目录:NSFileManager

文件或目录是使用文件的路径名的唯一标识。相对路径是相对于当前目录的路径名,每个路径名都是一个NSString对象,它既可以是相对路径,也可以是完整的路径。
完整路径也称为绝对路径,以斜线/开始,斜线实际上就是一个目录,为根目录。
特殊的代字符作为用户主目录的缩写。~linda表示 用户linda主目录的缩写,这个目录的路径可能是/User/linda。
单个代字符表示当前用户的主目录,路径名 ~/copy1.m会 引用存储在当前用户主目录中的文件copy1.m。

/  基本的文件操作
//假定存在一个名为testfile文件,内容如下:
//This is a test file with some data in it.Here is a another line of data.And a third.
//  Created by 强淑婷 on 2018/6/10.
//  Copyright © 2018年 强淑婷. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString *fName = @"testfile";
        NSFileManager *fm;
        NSDictionary *attr;
        
        //需要创建文件管理器的实例
        
        fm = [NSFileManager defaultManager];
        //首先确认测试文件存在
        if([fm fileExistsAtPath: fName] == NO){
            NSLog(@"File doesn't exist!");
            return 1;
        }
        //创建一个副本
        if([fm copyItemAtPath: fName toPath: @"newfile" error: NULL] ==NO){
            NSLog(@"File Copy failed!");
            return 2;
        }
        //测试两个文件是否一致
        if([fm contentsEqualAtPath: fName andPath: @"newfile"] == NO){
            NSLog(@"Files are Not Equal!");
            return 3;
        }
        //重命名副本
        if([fm moveItemAtPath: @"newfile" toPath: @"newfile2" error: NULL] == NO){
            NSLog(@"File rename Failed");
            return 4;
        }//可以用来将文件从一个目录移到另一个目录中(也可以用来移动整个目录)。如果两个路径引用同一目录的文件,其结果仅仅是重新命名这个文件。如本例
        //获取newfile2的大小
        if((attr = [fm attributesOfItemAtPath: @"newfile2" error :NULL]) == nil){
            NSLog(@"Couldn't get file attributes!");
            return 5;
        }
        NSLog(@"File size is %llu bytes", [[attr objectForKey: NSFileSize] unsignedLongLongValue]);
        //最后删除原始文件
        if([fm removeItemAtPath: fName error: NULL] == NO){
            NSLog(@"file removal failed");
            return 6;
        }
        NSLog(@"All operations were successful");
        //显示新创建的文件内容
        NSLog(@"%@", [NSString stringWithContentsOfFile: @"newfile2" encoding:NSUTF8StringEncoding error: NULL]);//将文件中的内容读入一个字符串对象,encoding参数指定文件中的字符数据如何表示。可供选择的参数定义在NSString.h头文件中。使用NSUTF8StringEncoding可说明文件包含常规的UTF8ASCII字符。        }
    return 0;
}
//在执行复制,重命名或移动操作时,目标文件不能是已存在的,否则操作将失败。

猜你喜欢

转载自blog.csdn.net/qiangshuting/article/details/80642806