在swift代码中使用fscanf()函数

时间:2015-09-07 15:07:15

标签: ios swift

在目标c中,我使用fscanf从文件中读取流并将值赋给变量:

int count;
char type[5];
fscanf(myFile, “count is %d, type is %4s ”,  &count, type)

我想在 swift 代码中做同样的事情,我试过:

//ERROR: Type annotation missing in pattern
//What type should I use for `count`?
var count
//ERROR: consecutive  statement on a line must  be separated by ‘;’
var type[5] : char
fscanf(myFile, “count is %d, type is %4s ”,  &count, type)

但是我上面显示了编译器错误。在swift中使用fscanf的正确方法是什么?

如果您知道任何快速实现同样的事情(不使用fscanf),那也会很棒!

1 个答案:

答案 0 :(得分:0)

我建议您使用Foundation框架解决方案来读取/写入文件数据。一个示例代码,用于读取我在我的应用程序中用于将文件流式传输到NSData的文件内容:

if let fileHandle = NSFileHandle(forReadingAtPath: "path/to/file") {
    fileHandle.seekToFileOffset(0)
    var data = fileHandle.readDataOfLength(5)
    var chars = [UInt8](count: 5, repeatedValue: 0)
    data.getBytes(&chars, length: 5)
    fileHandle.closeFile()
}

如果您需要从特定位置的文件中读取Int64数据:

if let fileHandle = NSFileHandle(forReadingAtPath: "path/to/file") {
    fileHandle.seekToFileOffset(0)
    var data = fileHandle.readDataOfLength(500)
    var intFetched: Int64 = 0
    let location = 100 // start at 101st character of file
    data.getBytes(&intFetched, range: NSMakeRange(location, 8))
    println(intFetched.littleEndian)
    fileHandle.closeFile()
}