File.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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 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(Errno.description())
  34. }
  35. return File(file)
  36. }
  37. public static func isDirectory(_ path: String) throws -> Bool {
  38. var s = stat()
  39. guard path.withCString({ stat($0, &s) }) == 0 else {
  40. throw FileError.isDirectoryFailed(Errno.description())
  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(Errno.description())
  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. guard let dir = path.withCString({ opendir($0) }) else {
  56. throw FileError.openDirFailed(Errno.description())
  57. }
  58. defer { closedir(dir) }
  59. var results = [String]()
  60. while let ent = readdir(dir) {
  61. var name = ent.pointee.d_name
  62. let fileName = withUnsafePointer(to: &name) { (ptr) -> String? in
  63. #if os(Linux)
  64. return String.fromCString([CChar](UnsafeBufferPointer<CChar>(start: UnsafePointer(unsafeBitCast(ptr, UnsafePointer<CChar>.self)), count: 256)))
  65. #else
  66. var buffer = [CChar](UnsafeBufferPointer(start: unsafeBitCast(ptr, to: UnsafePointer<CChar>.self), count: Int(ent.pointee.d_namlen)))
  67. buffer.append(0)
  68. return String(validatingUTF8: buffer)
  69. #endif
  70. }
  71. if let fileName = fileName {
  72. results.append(fileName)
  73. }
  74. }
  75. return results
  76. }
  77. let pointer: UnsafeMutablePointer<FILE>
  78. public init(_ pointer: UnsafeMutablePointer<FILE>) {
  79. self.pointer = pointer
  80. }
  81. public func close() -> Void {
  82. fclose(pointer)
  83. }
  84. public func read( data: inout [UInt8]) throws -> Int {
  85. if data.count <= 0 {
  86. return data.count
  87. }
  88. let count = fread(&data, 1, data.count, self.pointer)
  89. if count == data.count {
  90. return count
  91. }
  92. if feof(self.pointer) != 0 {
  93. return count
  94. }
  95. if ferror(self.pointer) != 0 {
  96. throw FileError.readFailed(Errno.description())
  97. }
  98. throw FileError.readFailed("Unknown file read error occured.")
  99. }
  100. public func write(data: [UInt8]) throws -> Void {
  101. if data.count <= 0 {
  102. return
  103. }
  104. try data.withUnsafeBufferPointer {
  105. if fwrite($0.baseAddress, 1, data.count, self.pointer) != data.count {
  106. throw FileError.writeFailed(Errno.description())
  107. }
  108. }
  109. }
  110. public func seek(offset: Int) throws -> Void {
  111. if fseek(self.pointer, offset, SEEK_SET) != 0 {
  112. throw FileError.seekFailed(Errno.description())
  113. }
  114. }
  115. }
  116. public func withNewFileOpenedForWriting<Result>(_ path: String, _ f: (File) throws -> Result) throws -> Result {
  117. return try withFileOpenedForMode(path, mode: "wb", f)
  118. }
  119. public func withFileOpenedForReading<Result>(_ path: String, _ f: (File) throws -> Result) throws -> Result {
  120. return try withFileOpenedForMode(path, mode: "rb", f)
  121. }
  122. public func withFileOpenedForWritingAndReading<Result>(_ path: String, _ f: (File) throws -> Result) throws -> Result {
  123. return try withFileOpenedForMode(path, mode: "r+b", f)
  124. }
  125. public func withFileOpenedForMode<Result>(_ path: String, mode: String, _ f: (File) throws -> Result) throws -> Result {
  126. let file = try File.openFileForMode(path, mode)
  127. defer {
  128. file.close()
  129. }
  130. return try f(file)
  131. }