遍历目录并获取所有文件和文件夹的路径

时间:2013-09-08 11:50:34

标签: macos cocoa loops file-management

你好我坚持这件事,我需要循环通过某个dir我需要从中获取所有文件名并将路径作为变量。

我知道如何创建循环,但是为了获取目录的内容,我没有。

感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:3)

试试这样:

// If your folder is a document.
NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:  @"Documents"];
// else you can give your folder path as well, if you know 
// for example like this NSString *docsDir = @"user/desktop/testFolder"

NSFileManager *localFileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:docsDir];
NSString *file = nil;
NSData *fileContents = [NSData data];
while ((file = [dirEnum nextObject])) 
{
   NSLog(@"your file name%@",file); // This will give your filename
   // Now for getting file path follow below.
   // here we are adding path to filename.
   NSString *fileNamePath = [docsDir stringByAppendingPathComponent:file];
   NSLog(@"your fileNamePath%@",fileNamePath); // This will give your filename path
   fileContents = [NSData dataWithContentsOfFile:fileNamePath]; // This will store file contents in form of bytes

}

希望有所帮助:)