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

Ios 在swift代码中使用fscanf()函数,ios,swift,Ios,Swift,在目标c中,我使用从文件中读取流并将值分配给变量: 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: consecutiv

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

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
),那也太好了

> P>我建议您使用基础框架解决方案来读取/写入文件数据。用于读取我在应用程序中用于将文件流式传输到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()
}

您的第一个问题是,变量声明是完全无效的Swift代码,因此您可以再看一次Swift手册的前几章。我读了,但我不知道应该在代码中声明什么类型。第二个错误听起来也很奇怪。我需要建议。如何读取整数
计数
?我应该为计数读取多少字节?这取决于整数的大小和尾数。在arm64上,它是8字节的little endian。在arm v6/7上,它是4字节的little endian。在第1个
数据之后。getBytes(&chars,length:5)
,如果我再次调用
getBytes(…)
,指针是否指向它读取的位置(即5)或自动重置到位置0?getBytes:length:将根据文档从位置0开始。使用getBytes:range:代替。我将字符定义为UInt8的数组。如果要读取整数,只需将其定义为Int64或Int32,并相应地将长度设置为8或4字节。如果文件将数据保存为big-endian。使用Int.byteSwapped属性来更正endianness,或者只使用.bigEndian/.littleEndian属性来获取正确的数据。读取文件时,请避免使用平台相关类型。