-
-
Save hsavit1/e4d80feb2d9556e50bcd to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import Foundation | |
| #if os(OSX) | |
| import Darwin | |
| #else | |
| import Glibc | |
| #endif | |
| let path = __FILE__ | |
| public struct ReadError : ErrorType {let reason: String} | |
| try NSString(string:"Foo").writeToFile("/tmp/text.txt", atomically: true, encoding: 4) | |
| func readFromPath(path: String) throws -> String { | |
| guard let fp: UnsafeMutablePointer<FILE> = fopen(path, "r") else { | |
| throw ReadError(reason: "Unable to open file") | |
| }; defer{fclose(fp)} | |
| let buffer: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer.alloc(1024); defer {buffer.dealloc(1024)} | |
| var bytes: [UInt8] = [] | |
| var totalCount = 0 | |
| repeat { | |
| let count: Int = fread(buffer, 1, 1024, fp) | |
| guard ferror(fp) == 0 else { | |
| throw ReadError(reason: "Encountered error while reading stream") | |
| } | |
| if count > 0 { | |
| bytes.appendContentsOf(Array(UnsafeBufferPointer(start:buffer, count:count))) | |
| totalCount += count | |
| } | |
| } while feof(fp) == 0 | |
| // let data = NSData(bytes: &bytes, length: totalCount) | |
| guard let string = String(bytesNoCopy: &bytes, length: totalCount, encoding: 4, freeWhenDone: true) else { | |
| throw ReadError(reason: "Could not convert to string") | |
| } | |
| return string | |
| } | |
| do { | |
| let string = try readFromPath(path) | |
| print(string) | |
| } catch {print(error)} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment