Last active
October 9, 2019 20:17
-
-
Save erica/4d31fed94f3668342623 to your computer and use it in GitHub Desktop.
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
import Glibc | |
// Swift 3 version here: https://gist.github.com/erica/7aee99db9753a1636e0fbed8d68b5845 | |
/* | |
Did a bunch of tweaks this morning: | |
removed == true (sorry Kametrixom!) | |
cleaned up both stringFromBytes and bytesFromString | |
changed fperror check to guard | |
replaced use of 1024 in several places with a single constant | |
*/ | |
// Convert String to UInt8 bytes | |
func bytesFromString(string: String) -> [UInt8] { | |
return Array(string.utf8) | |
} | |
// Convert UInt8 bytes to String | |
func stringFromBytes(bytes: UnsafeMutablePointer<UInt8>, count: Int) -> String { | |
return String((0..<count).map ({Character(UnicodeScalar(bytes[$0]))})) | |
} | |
// Use fopen/fwrite to output string | |
func writeStringToFile(string: String, path: String) -> Bool { | |
let fp = fopen(path, "w"); defer {fclose(fp)} | |
let byteArray = bytesFromString(string) | |
let count = fwrite(byteArray, 1, byteArray.count, fp) | |
return count == string.utf8.count | |
} | |
// Use fread to input string | |
func readStringFromFile(path: String) -> String { | |
let fp = fopen(path, "r"); defer {fclose(fp)} | |
var outputString = "" | |
let chunkSize = 1024 | |
let buffer: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer.alloc(chunkSize); defer {buffer.dealloc(chunkSize)} | |
repeat { | |
let count: Int = fread(buffer, 1, chunkSize, fp) | |
guard ferror(fp) == 0 else {break} | |
if count > 0 { | |
outputString += stringFromBytes(buffer, count: count) | |
} | |
} while feof(fp) == 0 | |
return outputString | |
} | |
// Simple test case writes to file and reads back in | |
let inputString = "Hello Sailor" | |
let path = "/tmp/test.txt" | |
if writeStringToFile(inputString, path: path) { | |
let outputString = readStringFromFile(path) | |
print("String:", outputString) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment