Created
December 31, 2016 01:48
-
-
Save zepedebo/c9870973c75c6268c743eaf32ba640ae to your computer and use it in GitHub Desktop.
Counting files in a directory with swift and external processes
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
// Set up the ls process | |
let lsProc = Process() | |
let lsStdout = Pipe() | |
lsProc.launchPath = "/bin/ls" | |
lsProc.standardOutput = lsStdout | |
// set up the wc process | |
let wcProc = Process() | |
let wcStdout = Pipe() | |
wcProc.launchPath = "/usr/bin/wc" | |
wcProc.arguments = ["-l"] | |
wcProc.standardInput = lsStdout | |
wcProc.standardOutput = wcStdout | |
// Go! | |
lsProc.launch() | |
wcProc.launch() | |
lsProc.waitUntilExit() | |
wcProc.waitUntilExit() | |
// Get the result | |
let data = wcStdout.fileHandleForReading.readDataToEndOfFile() | |
let stringData = String(data: data, encoding: String.Encoding.utf8) | |
print("File count = \(stringData?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment