1
0

File.swift 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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: ErrorType {
  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. let file = path.withCString({ pathPointer in mode.withCString({ fopen(pathPointer, $0) }) })
  33. guard file != nil else {
  34. throw FileError.OpenFailed(descriptionOfLastError())
  35. }
  36. return File(file)
  37. }
  38. public static func isDirectory(path: String) throws -> Bool {
  39. var s = stat()
  40. guard path.withCString({ stat($0, &s) }) == 0 else {
  41. throw FileError.IsDirectoryFailed(descriptionOfLastError())
  42. }
  43. return s.st_mode & S_IFMT == S_IFDIR
  44. }
  45. public static func currentWorkingDirectory() throws -> String {
  46. let path = getcwd(nil, 0)
  47. if path == nil {
  48. throw FileError.GetCurrentWorkingDirectoryFailed(descriptionOfLastError())
  49. }
  50. guard let result = String.fromCString(path) else {
  51. throw FileError.GetCurrentWorkingDirectoryFailed("Could not convert getcwd(...)'s result to String.")
  52. }
  53. return result
  54. }
  55. public static func exists(path: String) throws -> Bool {
  56. var buffer = stat()
  57. return path.withCString({ stat($0, &buffer) == 0 })
  58. }
  59. public static func list(path: String) throws -> [String] {
  60. let dir = path.withCString { opendir($0) }
  61. if dir == nil {
  62. throw FileError.OpenDirFailed(descriptionOfLastError())
  63. }
  64. defer { closedir(dir) }
  65. var results = [String]()
  66. while true {
  67. let ent = readdir(dir)
  68. if ent == nil {
  69. break
  70. }
  71. var name = ent.memory.d_name
  72. let fileName = withUnsafePointer(&name) { (ptr) -> String? in
  73. #if os(Linux)
  74. return String.fromCString([CChar](UnsafeBufferPointer<CChar>(start: UnsafePointer(unsafeBitCast(ptr, UnsafePointer<CChar>.self)), count: Int(NAME_MAX))))
  75. #else
  76. var buffer = [CChar](UnsafeBufferPointer(start: unsafeBitCast(ptr, UnsafePointer<CChar>.self), count: Int(ent.memory.d_namlen)))
  77. buffer.append(0)
  78. return String.fromCString(buffer)
  79. #endif
  80. }
  81. if let fileName = fileName {
  82. results.append(fileName)
  83. }
  84. }
  85. return results
  86. }
  87. let pointer: UnsafeMutablePointer<FILE>
  88. public init(_ pointer: UnsafeMutablePointer<FILE>) {
  89. self.pointer = pointer
  90. }
  91. public func close() -> Void {
  92. fclose(pointer)
  93. }
  94. public func read(inout data: [UInt8]) throws -> Int {
  95. if data.count <= 0 {
  96. return data.count
  97. }
  98. let count = fread(&data, 1, data.count, self.pointer)
  99. if count == data.count {
  100. return count
  101. }
  102. if feof(self.pointer) != 0 {
  103. return count
  104. }
  105. if ferror(self.pointer) != 0 {
  106. throw FileError.ReadFailed(File.descriptionOfLastError())
  107. }
  108. throw FileError.ReadFailed("Unknown file read error occured.")
  109. }
  110. public func write(data: [UInt8]) throws -> Void {
  111. if data.count <= 0 {
  112. return
  113. }
  114. try data.withUnsafeBufferPointer {
  115. if fwrite($0.baseAddress, 1, data.count, self.pointer) != data.count {
  116. throw FileError.WriteFailed(File.descriptionOfLastError())
  117. }
  118. }
  119. }
  120. public func seek(offset: Int) throws -> Void {
  121. if fseek(self.pointer, offset, SEEK_SET) != 0 {
  122. throw FileError.SeekFailed(File.descriptionOfLastError())
  123. }
  124. }
  125. private static func descriptionOfLastError() -> String {
  126. return String.fromCString(UnsafePointer(strerror(errno))) ?? "Error: \(errno)"
  127. }
  128. }
  129. extension File {
  130. public static func withNewFileOpenedForWriting<Result>(path: String, _ f: File throws -> Result) throws -> Result {
  131. return try withFileOpenedForMode(path, mode: "wb", f)
  132. }
  133. public static func withFileOpenedForReading<Result>(path: String, _ f: File throws -> Result) throws -> Result {
  134. return try withFileOpenedForMode(path, mode: "rb", f)
  135. }
  136. public static func withFileOpenedForWritingAndReading<Result>(path: String, _ f: File throws -> Result) throws -> Result {
  137. return try withFileOpenedForMode(path, mode: "r+b", f)
  138. }
  139. public static func withFileOpenedForMode<Result>(path: String, mode: String, _ f: File throws -> Result) throws -> Result {
  140. let file = try File.openFileForMode(path, mode)
  141. defer {
  142. file.close()
  143. }
  144. return try f(file)
  145. }
  146. }