Last active
January 18, 2016 21:28
-
-
Save ssoper/1c9b19d3ed28e0f5cb8c to your computer and use it in GitHub Desktop.
Cross-platform file reader in Swift
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
// 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