How to read user input or stdin in Swift for Linux?

How to read user input or character stream from standard input in Swift for Linux?

+7
linux swift
source share
3 answers

readLine () runs on Ubuntu 15:

[Readline] Returns Character reading from standard input to the end of the current line or until EOF is reached, or nil if EOF has already reached.

Example:

 print("\nEnter your name:\n") if let name = readLine() { print("\nHello \(name)!\n") } 

ed @swiftux: ~ / Swift / Scripts $. / testReadline

Enter your name:

Eric

Hi Eric!

readline() also works with | (pipe):

ed @swiftux: ~ / Swift / Scripts $ echo "Mike" | ./testReadline

Enter your name:

Hi Mike!


I also tried the classic way with NSFileHandle , but it hasn't been implemented yet:

fatal error: availableData not yet implemented: file Foundation / NSObjCRuntime.swift

+7
source share

If you import Glibc on Linux and Darwin.C on macOS, you can read one line at a time using the getline function.

This requires the c interop bit, but you can wrap it to represent a more Swifty interface. For example, the following function returns a generator that iterates over lines read from a file stream:

 #if os(Linux) import Glibc #else import Darwin.C #endif func lineGenerator(file:UnsafeMutablePointer<FILE>) -> AnyIterator<String> { return AnyIterator { () -> String? in var line:UnsafeMutablePointer<CChar>? = nil var linecap:Int = 0 defer { free(line) } let charactersWritten = getline(&line, &linecap, file) if charactersWritten > 0 { guard let line = line else { return nil } return String(validatingUTF8: line) } else { return nil } } } 

This works on Swift 3. You can find a small example project swiftecho that uses this from the command line.

+1
source share

I found a way to read characters from stdin , however it is not beautiful, but it shows what we can do with Glibc .

 import Glibc var buf = UnsafeMutablePointer<CChar>.alloc(32) fread(buf, 1, 32, stdin) // or fgets(buf, 32, stdin) 

and buf have input characters.

0
source share

All Articles