Skip to content

Instantly share code, notes, and snippets.

@alexcu
Created April 21, 2016 00:10
Show Gist options
  • Save alexcu/7d10f0351f117981f8ed385b4b8ab88e to your computer and use it in GitHub Desktop.
Save alexcu/7d10f0351f117981f8ed385b4b8ab88e to your computer and use it in GitHub Desktop.
Simple cross platform file parser for Swift
// Only import only funcs and structs we need to use
#if os(Linux)
// Linux uses Glibc
import struct Glibc.FILE
import func Glibc.fopen
import func Glibc.fgets
import func Glibc.fclose
#else
// OS X uses Darwin
import struct Darwin.C.FILE
import func Darwin.C.fopen
import func Darwin.C.fgets
import func Darwin.C.fclose
#endif
///
/// A simple, cross-platform file parser for reading in files
///
struct FileParser {
///
/// Reads the contents of a file into a string
/// - Parameter path: The path of the file to open
/// - Returns: An optional string of the file's contents, or `nil` if the file could
/// not be parsed (i.e., it was not readable)
///
static func readFile(path: String) -> String? {
let filePointer = fopen(path, "r")
guard filePointer != nil else {
return nil
}
// Read in 256b chunks
let length = 256
var result = String()
let buffer = UnsafeMutablePointer<Int8>.alloc(length)
while fgets(buffer, Int32(length), filePointer) != nil {
result += String.fromCString(buffer) ?? ""
}
fclose(filePointer)
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment