从/ .txt文件读取和写入整数

时间:2011-05-06 01:23:26

标签: objective-c file-io text-files

如何在文本文件中读取和写入整数,是否可以读取或写入多行,即处理多个整数?

感谢。

2 个答案:

答案 0 :(得分:2)

这当然是可能的;它只取决于文本文件的确切格式 阅读文本文件的内容很简单:

// If you want to handle an error, don't pass NULL to the following code, but rather an NSError pointer.
NSString *contents = [NSString stringWithContentsOfFile:@"/path/to/file" encoding:NSUTF8StringEncoding error:NULL];

创建一个包含整个文件的自动释放字符串。如果包含的所有文件都是整数,则可以写下:

NSInteger integer = [contents integerValue];

如果文件被分成多行(每行包含一个整数),则必须将其拆分:

NSArray *lines = [contents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *line in lines) {
    NSInteger currentInteger = [line integerValue];
    // Do something with the integer.
}

总的来说,这很简单。


回写文件同样容易。一旦你将你想要的东西操作回一个字符串,你就可以使用它:

NSString *newContents = ...; // New string.
[newContents writeToFile:@"/path/to/file" atomically:YES encoding:NSUTF8StringEncoding error:NULL];

您可以使用它来写入字符串。当然,您可以使用设置。将atomically设置为YES会导致它首先写入测试文件,验证它,然后将其复制以替换旧文件(这可确保如果发生某些故障,您将不会结束用腐败的文件)。如果需要,可以使用不同的编码(但强烈建议使用NSUTF8StringEncoding),如果要捕获错误(本质上应该是错误的),可以传入对NSError的引用方法。它看起来像这样:

NSError *error = nil;
[newContents writeToFile:@"someFile.txt" atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error) {
    // Some error has occurred. Handle it.
}

如需进一步阅读,请参阅NSString Class Reference

答案 1 :(得分:0)

如果您必须写入多行,请在构建\r\n字符串时使用newContents来指定放置换行符的位置。

NSMutableString *newContents = [[NSMutableString alloc] init];

for (/* loop conditions here */)
{
    NSString *lineString = //...do stuff to put important info for this line...
    [newContents appendString:lineString];
    [newContents appendString:@"\r\n"];
}
相关问题