Read and write an integer to/from a .txt file

浪子不回头ぞ 提交于 2019-12-11 22:22:21

问题


How can I read and write an integer to and from a text file, and is it possible to read or write to multiple lines, i.e., deal with multiple integers?

Thanks.


回答1:


This is certainly possible; it simply depends on the exact format of the text file.
Reading the contents of a text file is easy:

// 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];

That creates an autoreleased string containing the entire file. If all the file contains is an integer, you can just write this:

NSInteger integer = [contents integerValue];

If the file is split up into multiple lines (with each line containing one integer), you'll have to split it up:

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

Overall, it's very simple.


Writing back to a file is just as easy. Once you've manipulated what you wanted back into a string, you can just use this:

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

You can use that to write to a string. Of course, you can play with the settings. Setting atomically to YES causes it to write to a test file first, verify it, and then copy it over to replace the old file (this ensures that if some failure happens, you won't end up with a corrupt file). If you want, you can use a different encoding (though NSUTF8StringEncoding is highly recommended), and if you want to catch errors (which you should, essentially), you can pass in a reference to an NSError to the method. It would look something like this:

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

For further reading, consult the NSString Class Reference.




回答2:


If you have to write to multiple lines, use \r\n when building the newContents string to specify where line breaks are to be placed.

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"];
}


来源:https://stackoverflow.com/questions/5905891/read-and-write-an-integer-to-from-a-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!