Skip to content

Instantly share code, notes, and snippets.

@zepedebo
Created December 31, 2016 01:48
Show Gist options
  • Save zepedebo/c9870973c75c6268c743eaf32ba640ae to your computer and use it in GitHub Desktop.
Save zepedebo/c9870973c75c6268c743eaf32ba640ae to your computer and use it in GitHub Desktop.
Counting files in a directory with swift and external processes
// 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