File.swift 5.5 KB

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