[swift] 파일 크기 확인하기
import Foundation
func getFileSize(path: String) -> UInt64? {
do {
let fileAttributes = try FileManager.default.attributesOfItem(atPath: path)
if let fileSize = fileAttributes[.size] as? UInt64 {
return fileSize
}
} catch {
print("Error: \(error.localizedDescription)")
}
return nil
}
let filePath = "/path/to/file.txt"
if let fileSize = getFileSize(path: filePath) {
print("파일 크기: \(fileSize) bytes")
} else {
print("파일 크기를 가져올 수 없습니다.")
}
위 코드에서는 getFileSize
함수를 선언하여 파일 경로를 입력받고, 해당 파일의 크기를 반환합니다. FileManager.default.attributesOfItem(atPath: path)
를 통해 파일의 속성을 가져올 수 있으며, 속성 중 .size
를 통해 파일 크기를 가져올 수 있습니다.
위 예제 코드를 통해 파일 크기를 확인하고 출력해볼 수 있습니다.