递归列出给定目录下的所有文件和目录

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了递归列出给定目录下的所有文件和目录相关的知识,希望对你有一定的参考价值。

  1. /*
  2.  This is example code of how to walk a directory recurisively
  3.  and create a flat list of fully qualified names for all the files
  4.  and directories under the supplied virtual root directory.
  5.  */
  6.  
  7. #import <CoreServices/CoreServices.h>
  8. #import <AppKit/AppKit.h>
  9. #import <stdarg.h>
  10.  
  11. int main (int argc, const char * argv[])
  12. {
  13. int result = EXIT_SUCCESS;
  14. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  15. NSUserDefaults *args = [NSUserDefaults standardUserDefaults];
  16. NSString *dir = [args stringForKey:@"file"];
  17. NSMutableSet *contents = [[[NSMutableSet alloc] init] autorelease];
  18. NSFileManager *fm = [NSFileManager defaultManager];
  19. BOOL isDir;
  20. if (dir && ([fm fileExistsAtPath:dir isDirectory:&isDir] && isDir))
  21. {
  22. if (![dir hasSuffix:@"/"])
  23. {
  24. dir = [dir stringByAppendingString:@"/"];
  25. }
  26.  
  27. // this walks the |dir| recurisively and adds the paths to the |contents| set
  28. NSDirectoryEnumerator *de = [fm enumeratorAtPath:dir];
  29. NSString *fqn;
  30. while ((f = [de nextObject]))
  31. {
  32. // make the filename |f| a fully qualifed filename
  33. fqn = [dir stringByAppendingString:f];
  34. if ([fm fileExistsAtPath:fqn isDirectory:&isDir] && isDir)
  35. {
  36. // append a / to the end of all directory entries
  37. fqn = [fqn stringByAppendingString:@"/"];
  38. }
  39. [contents addObject:fqn];
  40. }
  41.  
  42. NSString *fn;
  43. // here we sort the |contents| before we display them
  44. for ( fn in [[contents allObjects] sortedArrayUsingSelector:@selector(compare:)] )
  45. {
  46. printf("%s ",[fn UTF8String]);
  47. }
  48. }
  49. else
  50. {
  51. printf("%s must be directory and must exist ", [dir UTF8String]);
  52. result = EXIT_FAILURE;
  53. }
  54.  
  55. [pool release];
  56. return result;
  57. }

以上是关于递归列出给定目录下的所有文件和目录的主要内容,如果未能解决你的问题,请参考以下文章

递归法列出目录中的所有文件

IO流 列出目录下所有内容-递归

案例:遍历目录

列出/etc目录下的所有文件命令

递归列出一个目录下所有的文件夹和文件

C#,给定一个目录,遍历该目录下的所有文件、文件夹