File.swift 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. //
  2. // File.swift
  3. // Swifter
  4. //
  5. // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. #if os(Linux)
  8. import Glibc
  9. #else
  10. import Foundation
  11. #endif
  12. public enum FileError: ErrorProtocol {
  13. case openFailed(String)
  14. case writeFailed(String)
  15. case readFailed(String)
  16. case seekFailed(String)
  17. case getCurrentWorkingDirectoryFailed(String)
  18. case isDirectoryFailed(String)
  19. case openDirFailed(String)
  20. }
  21. public class File {
  22. public static func openNewForWriting(_ path: String) throws -> File {
  23. return try openFileForMode(path, "wb")
  24. }
  25. public static func openForReading(_ path: String) throws -> File {
  26. return try openFileForMode(path, "rb")
  27. }
  28. public static func openForWritingAndReading(_ path: String) throws -> File {
  29. return try openFileForMode(path, "r+b")
  30. }
  31. public static func openFileForMode(_ path: String, _ mode: String) throws -> File {
  32. guard let file = path.withCString({ pathPointer in mode.withCString({ fopen(pathPointer, $0) }) }) else {
  33. throw FileError.openFailed(descriptionOfLastError())
  34. }
  35. return File(file)
  36. }
  37. public static func isDirectory(_ path: String) throws -> Bool {
  38. var s = stat()
  39. guard stat(path, &s) == 0 else {
  40. throw FileError.isDirectoryFailed(descriptionOfLastError())
  41. }
  42. return s.st_mode & S_IFMT == S_IFDIR
  43. }
  44. public static func currentWorkingDirectory() throws -> String {
  45. guard let path = getcwd(nil, 0) else {
  46. throw FileError.getCurrentWorkingDirectoryFailed(descriptionOfLastError())
  47. }
  48. return String(cString: path)
  49. }
  50. public static func exists(_ path: String) throws -> Bool {
  51. var buffer = stat()
  52. return path.withCString({ stat($0, &buffer) == 0 })
  53. }
  54. public static func list(_ path: String) throws -> [String] {
  55. let dir = path.withCString { opendir($0) }
  56. if dir == nil {
  57. throw FileError.openDirFailed(descriptionOfLastError())
  58. }
  59. defer { closedir(dir) }
  60. var results = [String]()
  61. while true {
  62. guard let ent = readdir(dir) else {
  63. break
  64. }
  65. var name = ent.pointee.d_name
  66. let fileName = withUnsafePointer(&name) { (ptr) -> String? in
  67. #if os(Linux)
  68. return String.fromCString([CChar](UnsafeBufferPointer<CChar>(start: UnsafePointer(unsafeBitCast(ptr, UnsafePointer<CChar>.self)), count: 256)))
  69. #else
  70. var buffer = [CChar](UnsafeBufferPointer(start: unsafeBitCast(ptr, to: UnsafePointer<CChar>.self), count: Int(ent.pointee.d_namlen)))
  71. buffer.append(0)
  72. return String(validatingUTF8: buffer)
  73. #endif
  74. }
  75. if let fileName = fileName {
  76. results.append(fileName)
  77. }
  78. }
  79. return results
  80. }
  81. internal let pointer: UnsafeMutablePointer<FILE>
  82. public init(_ pointer: UnsafeMutablePointer<FILE>) {
  83. self.pointer = pointer
  84. }
  85. public func close() -> Void {
  86. fclose(pointer)
  87. }
  88. public func read(_ data: inout [UInt8]) throws -> Int {
  89. if data.count <= 0 {
  90. return data.count
  91. }
  92. let count = fread(&data, 1, data.count, self.pointer)
  93. if count == data.count {
  94. return count
  95. }
  96. if feof(self.pointer) != 0 {
  97. return count
  98. }
  99. if ferror(self.pointer) != 0 {
  100. throw FileError.readFailed(File.descriptionOfLastError())
  101. }
  102. throw FileError.readFailed("Unknown file read error occured.")
  103. }
  104. public func write(_ data: [UInt8]) throws -> Void {
  105. if data.count <= 0 {
  106. return
  107. }
  108. try data.withUnsafeBufferPointer {
  109. if fwrite($0.baseAddress, 1, data.count, self.pointer) != data.count {
  110. throw FileError.writeFailed(File.descriptionOfLastError())
  111. }
  112. }
  113. }
  114. public func seek(_ offset: Int) throws -> Void {
  115. if fseek(self.pointer, offset, SEEK_SET) != 0 {
  116. throw FileError.seekFailed(File.descriptionOfLastError())
  117. }
  118. }
  119. private static func descriptionOfLastError() -> String {
  120. return String(cString: UnsafePointer(strerror(errno))) ?? "Error: \(errno)"
  121. }
  122. }
  123. extension File {
  124. public static func withNewFileOpenedForWriting<Result>(_ path: String, _ f: (File) throws -> Result) throws -> Result {
  125. return try withFileOpenedForMode(path, mode: "wb", f)
  126. }
  127. public static func withFileOpenedForReading<Result>(_ path: String, _ f: (File) throws -> Result) throws -> Result {
  128. return try withFileOpenedForMode(path, mode: "rb", f)
  129. }
  130. public static func withFileOpenedForWritingAndReading<Result>(_ path: String, _ f: (File) throws -> Result) throws -> Result {
  131. return try withFileOpenedForMode(path, mode: "r+b", f)
  132. }
  133. public static func withFileOpenedForMode<Result>(_ path: String, mode: String, _ f: (File) throws -> Result) throws -> Result {
  134. let file = try File.openFileForMode(path, mode)
  135. defer {
  136. file.close()
  137. }
  138. return try f(file)
  139. }
  140. }