Search code examples
iosobjective-cnsurlnsfilemanager

How to delete all files inside a folder whose file size is less then a certain size (Bytes)


I've a folder call "Recorded". Inside it say, there are 10 audio files (.m4a) right now. The size of these files (Bytes) are may be different or same. Now I want to delete those files inside that folder whose size are less then 542 Bytes.

I can delete a file from that folder sending "fileName":

- (void)removeAudioFile:(NSString *) fileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSString *folder = [documentsPath stringByAppendingPathComponent:@"/Recorded"];
    NSString *filePath = [folder stringByAppendingPathComponent:fileName];
    NSError *error;
    BOOL success = [fileManager removeItemAtPath:filePath error:&error];
    if (success)
    {

    }
    else
    {
        NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
    }
}

I can measure a specific file size inside that folder:

-(void) FileSize:(NSString *) urlPath
{
    NSError *attributesError;
    NSString *path = [urlPath stringByAppendingString:@"/22Nov2014_02.19.50AM.m4a"];

    unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:path error:&attributesError] fileSize];

    NSLog(@"file size %lld", fileSize);
}

I can delete all file inside that folder:

-(void) deleteAllFiles:(NSString *) urlPath
{
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSArray *fileArray = [fileMgr contentsOfDirectoryAtPath:urlPath error:nil];
    for (NSString *filename in fileArray)
    {
        [fileMgr removeItemAtPath:[urlPath stringByAppendingPathComponent:filename] error:NULL];
    }
}

But I want to delete those files inside "Recorded" whose file size is less than 542 Bytes. If you understand my question, please reply me. Thanks a lot in advanced.


Solution

  • Simply check if the file size is under 542 bytes, and if so remove it:

    -(void) deleteAllFiles:(NSString *) urlPath
    {
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        NSArray *fileArray = [fileMgr contentsOfDirectoryAtPath:urlPath error:nil];
        for (NSString *filename in fileArray)
        {
            NSString *filePath = [path stringByAppendingPathComponent:filename];
            unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil] fileSize];
            if (fileSize < 542) [fileMgr removeItemAtPath:filePath error:NULL];
        }
    }