我有这种类型的文件:
@firstTablel:1#one#two#three#four; 2#苹果#塔#花#机器人;
这是我的csv文件的一个示例...“firstTable”是我的表,1和2是我的两个项目的两个id。
如何在目标c中读取此文件?你能救我吗?
答案 0 :(得分:12)
Cocoa for Scientists在阅读CSV文件方面发表了很好的帖子:http://macresearch.org/cocoa-scientists-part-xxvi-parsing-csv-data
在你的情况下,你会做类似的事情:
NSString *fileString = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:outError];
if (!fileString) {
NSLog(@"Error reading file.");
}
NSScanner *scanner = [NSScanner scannerWithString:fileString];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"\n#; "]];
NSString *id = nil, *hashOne = nil, *hashTwo = nil, *hashThree = nil, *hashFour = nil;
while ([scanner scanUpToString:@"#" intoString:&id] && [scanner scanUpToString:@"#" intoString:&hashOne] && [scanner scanUpToString:@"#" intoString:&hashTwo] && [scanner scanUpToString:@"#" intoString:&hashThree] && [scanner scanUpToString:@";" intoString:&hashFour]) {
// Process the values as needed.
NSLog(@"id:%@, 1:%@, 2:%@, 3:%@:, 4:%@", id, hashOne, hashTwo, hashThree, hashFour);
}
在您提供的样本上,将打印:
2011-03-31 13:55:07.846 Stephen[39304:903] id:1, 1:one, 2:two, 3:three:, 4:four
2011-03-31 13:55:07.849 Stephen[39304:903] id:2, 1:apple, 2:tower, 3:flower:, 4:robot