swift中用C的方式读取一个文件,获得文件的数据流 byte/char 数组
func readFile(filename: NSString) -> UnsafeMutablePointer<CUnsignedChar>? {
let fp = fopen(filename.UTF8String, "r")
if fp == nil {
print("Open File fail!")
return nil
}
fseek(fp, 0, SEEK_END)
let length = ftell(fp)
fseek(fp, 0, SEEK_SET)
let buffer = UnsafeMutablePointer<CUnsignedChar>.alloc(length)
fread(buffer, sizeof(CUnsignedChar), length, fp)
fclose(fp)
return buffer
}
将数据写到文件中
func writeFile(buffer:UnsafeMutablePointer<CUnsignedChar>,count:Int, toPath pathString: String){
let fp = fopen(pathString, "w");
fwrite(buffer, sizeof(CUnsignedChar), count, fp)
fflush(fp)//这个得加上,立即把io里面的数据写到硬盘上去
}
其实c的函数在swift也是可以很好的使用的