ArkSysFile.swift 874 B

123456789101112131415161718192021222324252627
  1. import CSystem
  2. extension ArkSys {
  3. public struct File {
  4. /// Reads the entire contents of a file as a String.
  5. public static func readString(_ path: String) -> String? {
  6. guard let fp = fopen(path, "r") else { return nil }
  7. defer { fclose(fp) }
  8. var result = ""
  9. var buf = [CChar](repeating: 0, count: 256)
  10. while fgets(&buf, 256, fp) != nil {
  11. result += String(cString: buf)
  12. }
  13. return result
  14. }
  15. /// Writes a String to a file, overwriting existing contents.
  16. public static func writeString(_ path: String, content: String) -> Bool {
  17. guard let fp = fopen(path, "w") else { return false }
  18. defer { fclose(fp) }
  19. return fputs(content, fp) >= 0
  20. }
  21. }
  22. }