Question

I need some help with displaying the number of .txt files in a folder.

I can look in a folder for the .txt files:

 NSURL *fileURL = [NSURL fileURLWithPath:filePath];

NSString *theFolder= [fileURL path];

NSError *error;

NSString *file;

NSEnumerator *files = [[[NSFileManager defaultManager]
                        contentsOfDirectoryAtPath:theFolder error:&error] objectEnumerator];
while(file = [files nextObject] ) {
    if( [[file pathExtension] isEqualToString:@"txt"] ) {

... and I can display the total number of files in the folder:

 NSArray *filelist= [[NSFileManager defaultManager]
                     contentsOfDirectoryAtPath:myString error:nil];

                    NSInteger count = [filelist count];
                    [totalFiles setIntegerValue:count];

I'm stumped on how to only display the number of .txt files in the given folder.

Thanks for the help.

Was it helpful?

Solution

You could do something like this:

NSEnumerator *files = [[[NSFileManager defaultManager]
                        contentsOfDirectoryAtPath:theFolder error:&error] objectEnumerator];
NSMutableArray *arrayOfTxtFiles = [[NSMutableArray alloc] init];
while(file = [files nextObject] ) {
    if( [[file pathExtension] isEqualToString:@"txt"] ) {
         [arrayOfTxtFiles addObject: file];
    }
}

NSLog( @"count of .txt files is %d", [arrayOfTxtFiles count] );

arrayOfTxtFiles contains all the .txt filenames.

I'm basing my code off your first code snippet, although there may be an even more elegant way to do what you're trying to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top