iOS OC C

文件操作

查看目录下所有文件、循环遍历递归

920 发布: 2015/11/5 13:18 本文总阅读量

FileManager.m

#import "FileManager.h"

@implementation FileManager

+ (void)showFiles:(NSString *)path;{

    // 1.判断文件还是目录
    NSFileManager * fileManger = [NSFileManager  defaultManager];
    BOOL isDir = NO;
    BOOL isExist = [fileManger fileExistsAtPath:path isDirectory:&isDir];

    if (isExist) {
        // 2. 判断是不是目录
        if (isDir) {
            NSArray * dirArray = [fileManger contentsOfDirectoryAtPath:path error:nil];
            NSString * subPath = nil;
            for (NSString * str  in dirArray) {
                subPath  = [path  stringByAppendingPathComponent:str];
                BOOL issubDir = NO;
                [fileManger  fileExistsAtPath:subPath isDirectory:&issubDir];
                [self  showFiles:subPath];
            }
        }else{
            NSLog(@"%@",path);
        }
    }else{
        NSLog(@"你打印的是目录或者不存在");
    }
}
@end

main.m

#import 
#import "FileManager.h"

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

    @autoreleasepool {

        NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"desktop/new new"];// 更改:自己规定路径
        [FileManager  showFiles:path];
    }

     return 0;
}