Recursively list all files and directories below a given directory


/ Published in: Objective C
Save to your folder(s)



Copy this code and paste it in your HTML
  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\n",[fn UTF8String]);
  47. }
  48. }
  49. else
  50. {
  51. printf("%s must be directory and must exist\n", [dir UTF8String]);
  52. result = EXIT_FAILURE;
  53. }
  54.  
  55. [pool release];
  56. return result;
  57. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.