0

我想从我定义的自定义文件“player.geo”中一一读取一些浮点值。

player.geo 是我使用 Xcode 4 创建的文件(“文件”>“新建”菜单中的“空文件”)

我目前正在尝试这样做:

- (id) initWithGeometryFile:(NSString *) nameOfFile
{
    NSFileHandle *geoFile = NULL;

    NSString *geoFilePath = [[NSBundle mainBundle] pathForResource:@"player" ofType:@"geo"];

    geoFile = [NSFileHandle fileHandleForReadingAtPath:geoFilePath];

    if(geoFile == NULL)
    {
        NSLog(@"Failed to open file.");
    }
    else
    {
        NSLog(@"Opening %@ successful", nameOfFile);

        NSMutableData *fileData = [[NSMutableData alloc] initWithData:[geoFile readDataOfLength:4]];

        float firstValue;
        [fileData getBytes:&firstValue length:sizeof(float)];

        NSLog(@"First value in file %@ is %f", nameOfFile, firstValue);
    }

    return self;
}

我没有得到 -64.0 的预期值,而是得到 0.0。

这是正确的方法吗?

我真的必须将文件作为字符串读取,然后解析浮点字符串内容以获得浮点值吗?

4

1 回答 1

1

NSData对象处理原始字节,而不是字符串。如果您在 txt 文件中输入字符串,这将不起作用。如果您正在使用NSData对象,那么您将需要首先使用数据对象方法写入数据,例如writeToFile:atomically:.

或者,您可以使用 NSString 函数stringWithContentsOfFilecomponentsSeperatedByString在其自己的行上生成一个包含每个字符串的 NSArray,如下所示:

NSString *tmp;
NSArray *lines;
lines = [[NSString stringWithContentsOfFile:@"testFileReadLines.txt"] 
                   componentsSeparatedByString:@"\n"];

NSEnumerator *nse = [lines objectEnumerator];
while(tmp = [nse nextObject]) {
    NSLog(@"%@", tmp);
}
于 2011-08-06T15:12:54.223 回答