Skip to content

Instantly share code, notes, and snippets.

@ssoper
Last active January 18, 2016 21:28
Show Gist options
  • Save ssoper/1c9b19d3ed28e0f5cb8c to your computer and use it in GitHub Desktop.
Save ssoper/1c9b19d3ed28e0f5cb8c to your computer and use it in GitHub Desktop.
Cross-platform file reader in Swift
// Latest snapshot, 01-11-2016, seems to have fixed the missing SEEK_END pointer yet
// made NSData(contentsOfFile:) a missing symbol on Linux
func contents(path: String) -> String? {
let fp: UnsafeMutablePointer<FILE> = fopen(path, "r")
defer { fclose(fp) }
fseek(fp, 0, SEEK_END)
let fileSize = ftell(fp)
rewind(fp)
var buffer = UnsafeMutablePointer<CChar>.alloc(fileSize+1)
defer { buffer.destroy() }
fread(buffer, sizeof(CChar), fileSize, fp)
buffer[fileSize] = 0
guard let str = String.fromCString(buffer) else {
return nil
}
return str
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment