Created
February 7, 2016 05:30
-
-
Save rayfix/66b0a822648c87326645 to your computer and use it in GitHub Desktop.
Getting the Size of a file or directory in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.swift | |
// findsize | |
// | |
// Created by Ray Fix on 2/6/16. | |
// Copyright © 2016 Neko Labs. All rights reserved. | |
// | |
import Foundation | |
enum FileErrors : ErrorType { | |
case BadEnumeration | |
case BadResource | |
} | |
func findSize(path: String) throws -> UInt64 { | |
let fullPath = (path as NSString).stringByExpandingTildeInPath | |
let fileAttributes: NSDictionary = try NSFileManager.defaultManager().attributesOfItemAtPath(fullPath) | |
if fileAttributes.fileType() == NSFileTypeRegular { | |
return fileAttributes.fileSize() | |
} | |
let url = NSURL(fileURLWithPath: fullPath) | |
guard let directoryEnumerator = NSFileManager.defaultManager().enumeratorAtURL(url, includingPropertiesForKeys: [NSURLFileSizeKey], options: [.SkipsHiddenFiles], errorHandler: nil) else { throw FileErrors.BadEnumeration } | |
var total: UInt64 = 0 | |
for (index, object) in directoryEnumerator.enumerate() { | |
guard let fileURL = object as? NSURL else { throw FileErrors.BadResource } | |
var fileSizeResource: AnyObject? | |
try fileURL.getResourceValue(&fileSizeResource, forKey: NSURLFileSizeKey) | |
guard let fileSize = fileSizeResource as? NSNumber else { continue } | |
total += fileSize.unsignedLongLongValue | |
if index % 1000 == 0 { | |
print(".", terminator: "") | |
} | |
} | |
return total | |
} | |
if Process.arguments.count < 2 { | |
print("usage: findsize filenames") | |
} | |
do { | |
let totalSize = try Process.arguments.dropFirst().reduce(UInt64(0)) { $0 + (try findSize($1)) } | |
let formatter = NSNumberFormatter() | |
formatter.numberStyle = .DecimalStyle | |
formatter.formatterBehavior = .Behavior10_4 | |
let pretty = formatter.stringFromNumber(NSNumber(unsignedLongLong: totalSize)) | |
print("\nTotal Size: \(pretty)") | |
} | |
catch let error as NSError { | |
print(error.localizedDescription) | |
} | |
catch { | |
print(error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment