Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get directory contents in date modified order

Is there an method to get the contents of a folder in a particular order? I'd like an array of file attribute dictionaries (or just file names) ordered by date modified.

Right now, I'm doing it this way:

  • get an array with the file names
  • get the attributes of each file
  • store the file's path and modified date in a dictionary with the date as a key

Next I have to output the dictionary in date order, but I wondered if there's an easier way? If not, is there a code snippet somewhere which will do this for me?

Thanks.

like image 739
nevan king Avatar asked Oct 06 '09 05:10

nevan king


People also ask

How would you list all contents of a directory sorted by last modification time?

The 'ls' command lists all files and folders in a directory at the command line, but by default ls returns a list in alphabetical order. With a simple command flag, you can have ls sort by date instead, showing the most recently modified items at the top of the ls command results.

How do I sort files by date modified?

Open File Explorer and navigate to the location where your files are stored. Sort files by Date Modified (Recent files first). Hold Shift key and click on the Name column. This will bring folders at the top with files sorted with Date Modified.

How do you get a directory listing sorted by creation date in Python?

To get a directory listing sorted by creation date in Python, you can call os. listdir() to get a list of the filenames. Then call os. stat() for each one to get the creation time and finally sort against the creation time.


2 Answers

nall's code above pointed me in the right direction, but I think there are some mistakes in the code as posted above. For instance:

  1. Why is filesAndProperties allocated using NMutableDictonary rather than an NSMutableArray?

  2.  NSDictionary* properties = [[NSFileManager defaultManager]                                         attributesOfItemAtPath:NSFileModificationDate                                         error:&error];  
    The code above is passing the wrong parameter for attributesOfItemAtPath - it should be attributesOfItemAtPath:path

  3. Your are sorting the files array, but you should be sorting filesAndProperties.


I have implemented the same, with corrections, and using blocks and posted below:

     NSArray *searchPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);     NSString* documentsPath = [searchPaths objectAtIndex: 0];       NSError* error = nil;     NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];     if(error != nil) {         NSLog(@"Error in reading files: %@", [error localizedDescription]);         return;     }      // sort by creation date     NSMutableArray* filesAndProperties = [NSMutableArray arrayWithCapacity:[filesArray count]];     for(NSString* file in filesArray) {         NSString* filePath = [iMgr.documentsPath stringByAppendingPathComponent:file];         NSDictionary* properties = [[NSFileManager defaultManager]                                     attributesOfItemAtPath:filePath                                     error:&error];         NSDate* modDate = [properties objectForKey:NSFileModificationDate];          if(error == nil)         {             [filesAndProperties addObject:[NSDictionary dictionaryWithObjectsAndKeys:                                            file, @"path",                                            modDate, @"lastModDate",                                            nil]];                          }     }          // sort using a block         // order inverted as we want latest date first     NSArray* sortedFiles = [filesAndProperties sortedArrayUsingComparator:                             ^(id path1, id path2)                             {                                                                // compare                                  NSComparisonResult comp = [[path1 objectForKey:@"lastModDate"] compare:                                                            [path2 objectForKey:@"lastModDate"]];                                 // invert ordering                                 if (comp == NSOrderedDescending) {                                     comp = NSOrderedAscending;                                 }                                 else if(comp == NSOrderedAscending){                                     comp = NSOrderedDescending;                                 }                                 return comp;                                                             }];  
like image 57
M-V Avatar answered Oct 02 '22 15:10

M-V


How about this:

// Application documents directory NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];  NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:documentsURL                                                           includingPropertiesForKeys:@[NSURLContentModificationDateKey]                                                                              options:NSDirectoryEnumerationSkipsHiddenFiles                                                                                error:nil];  NSArray *sortedContent = [directoryContent sortedArrayUsingComparator:                         ^(NSURL *file1, NSURL *file2)                         {                             // compare                             NSDate *file1Date;                             [file1 getResourceValue:&file1Date forKey:NSURLContentModificationDateKey error:nil];                              NSDate *file2Date;                             [file2 getResourceValue:&file2Date forKey:NSURLContentModificationDateKey error:nil];                              // Ascending:                             return [file1Date compare: file2Date];                             // Descending:                             //return [file2Date compare: file1Date];                         }]; 
like image 44
Ivan Kovacevic Avatar answered Oct 02 '22 15:10

Ivan Kovacevic