File.swift 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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(Errno.description())
  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(Errno.description())
  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(Errno.description())
  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(Errno.description())
  63. }
  64. defer { closedir(dir) }
  65. var results = [String]()
  66. while case let ent = readdir(dir) where ent != nil {
  67. var name = ent.memory.d_name
  68. let fileName = withUnsafePointer(&name) { (ptr) -> String? in
  69. #if os(Linux)
  70. return String.fromCString([CChar](UnsafeBufferPointer<CChar>(start: UnsafePointer(unsafeBitCast(ptr, UnsafePointer<CChar>.self)), count: Int(NAME_MAX))))
  71. #else
  72. var buffer = [CChar](UnsafeBufferPointer(start: unsafeBitCast(ptr, UnsafePointer<CChar>.self), count: Int(ent.memory.d_namlen)))
  73. buffer.append(0)
  74. return String.fromCString(buffer)
  75. #endif
  76. }
  77. if let fileName = fileName {
  78. results.append(fileName)
  79. }
  80. }
  81. return results
  82. }
  83. let pointer: UnsafeMutablePointer<FILE>
  84. public init(_ pointer: UnsafeMutablePointer<FILE>) {
  85. self.pointer = pointer
  86. }
  87. public func close() -> Void {
  88. fclose(pointer)
  89. }
  90. public func read(inout data: [UInt8]) throws -> Int {
  91. if data.count <= 0 {
  92. return data.count
  93. }
  94. let count = fread(&data, 1, data.count, self.pointer)
  95. if count == data.count {
  96. return count
  97. }
  98. if feof(self.pointer) != 0 {
  99. return count
  100. }
  101. if ferror(self.pointer) != 0 {
  102. throw FileError.ReadFailed(Errno.description())
  103. }
  104. throw FileError.ReadFailed("Unknown file read error occured.")
  105. }
  106. public func write(data: [UInt8]) throws -> Void {
  107. if data.count <= 0 {
  108. return
  109. }
  110. try data.withUnsafeBufferPointer {
  111. if fwrite($0.baseAddress, 1, data.count, self.pointer) != data.count {
  112. throw FileError.WriteFailed(Errno.description())
  113. }
  114. }
  115. }
  116. public func seek(offset: Int) throws -> Void {
  117. if fseek(self.pointer, offset, SEEK_SET) != 0 {
  118. throw FileError.SeekFailed(Errno.description())
  119. }
  120. }
  121. }
  122. public func withNewFileOpenedForWriting<Result>(path: String, _ f: File throws -> Result) throws -> Result {
  123. return try withFileOpenedForMode(path, mode: "wb", f)
  124. }
  125. public func withFileOpenedForReading<Result>(path: String, _ f: File throws -> Result) throws -> Result {
  126. return try withFileOpenedForMode(path, mode: "rb", f)
  127. }
  128. public func withFileOpenedForWritingAndReading<Result>(path: String, _ f: File throws -> Result) throws -> Result {
  129. return try withFileOpenedForMode(path, mode: "r+b", f)
  130. }
  131. public func withFileOpenedForMode<Result>(path: String, mode: String, _ f: File throws -> Result) throws -> Result {
  132. let file = try File.openFileForMode(path, mode)
  133. defer {
  134. file.close()
  135. }
  136. return try f(file)
  137. }