File.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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: Error {
  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 var PATH_SEPARATOR = "/"
  23. public static func openNewForWriting(_ path: String) throws -> File {
  24. return try openFileForMode(path, "wb")
  25. }
  26. public static func openForReading(_ path: String) throws -> File {
  27. return try openFileForMode(path, "rb")
  28. }
  29. public static func openForWritingAndReading(_ path: String) throws -> File {
  30. return try openFileForMode(path, "r+b")
  31. }
  32. public static func openFileForMode(_ path: String, _ mode: String) throws -> File {
  33. guard let file = path.withCString({ pathPointer in mode.withCString({ fopen(pathPointer, $0) }) }) 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 stat(path, &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. guard let path = getcwd(nil, 0) else {
  47. throw FileError.getCurrentWorkingDirectoryFailed(descriptionOfLastError())
  48. }
  49. return String(cString: path)
  50. }
  51. public static func exists(_ path: String) throws -> Bool {
  52. var buffer = stat()
  53. return path.withCString({ stat($0, &buffer) == 0 })
  54. }
  55. public static func list(_ path: String) throws -> [String] {
  56. let dir = path.withCString { opendir($0) }
  57. if dir == nil {
  58. throw FileError.openDirFailed(descriptionOfLastError())
  59. }
  60. defer { closedir(dir) }
  61. var results = [String]()
  62. while true {
  63. guard let ent = readdir(dir) else {
  64. break
  65. }
  66. var name = ent.pointee.d_name
  67. let fileName = withUnsafePointer(to: &name) { (ptr) -> String? in
  68. #if os(Linux)
  69. return String.fromCString([CChar](UnsafeBufferPointer<CChar>(start: UnsafePointer(unsafeBitCast(ptr, UnsafePointer<CChar>.self)), count: 256)))
  70. #else
  71. var buffer = [CChar](UnsafeBufferPointer(start: unsafeBitCast(ptr, to: UnsafePointer<CChar>.self), count: Int(ent.pointee.d_namlen)))
  72. buffer.append(0)
  73. return String(validatingUTF8: buffer)
  74. #endif
  75. }
  76. if let fileName = fileName {
  77. results.append(fileName)
  78. }
  79. }
  80. return results
  81. }
  82. internal let pointer: UnsafeMutablePointer<FILE>
  83. public init(_ pointer: UnsafeMutablePointer<FILE>) {
  84. self.pointer = pointer
  85. }
  86. public func close() -> Void {
  87. fclose(pointer)
  88. }
  89. public func read(_ data: inout [UInt8]) throws -> Int {
  90. if data.count <= 0 {
  91. return data.count
  92. }
  93. let count = fread(&data, 1, data.count, self.pointer)
  94. if count == data.count {
  95. return count
  96. }
  97. if feof(self.pointer) != 0 {
  98. return count
  99. }
  100. if ferror(self.pointer) != 0 {
  101. throw FileError.readFailed(File.descriptionOfLastError())
  102. }
  103. throw FileError.readFailed("Unknown file read error occured.")
  104. }
  105. public func write(_ data: [UInt8]) throws -> Void {
  106. if data.count <= 0 {
  107. return
  108. }
  109. try data.withUnsafeBufferPointer {
  110. if fwrite($0.baseAddress, 1, data.count, self.pointer) != data.count {
  111. throw FileError.writeFailed(File.descriptionOfLastError())
  112. }
  113. }
  114. }
  115. public func seek(_ offset: Int) throws -> Void {
  116. if fseek(self.pointer, offset, SEEK_SET) != 0 {
  117. throw FileError.seekFailed(File.descriptionOfLastError())
  118. }
  119. }
  120. private static func descriptionOfLastError() -> String {
  121. return String(cString: UnsafePointer(strerror(errno)))
  122. }
  123. }
  124. public func withNewFileOpenedForWriting<Result>(path: String, _ f: (File) throws -> Result) throws -> Result {
  125. return try withFileOpenedForMode(path, "wb", f)
  126. }
  127. public func withFileOpenedForReading<Result>(path: String, _ f: (File) throws -> Result) throws -> Result {
  128. return try withFileOpenedForMode(path, "rb", f)
  129. }
  130. public func withFileOpenedForWritingAndReading<Result>(path: String, _ f: (File) throws -> Result) throws -> Result {
  131. return try withFileOpenedForMode(path, "r+b", f)
  132. }
  133. public 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. }