Reputation: 31
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.
Upvotes: 1
Views: 3110
Reputation: 3001
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"];
}
Upvotes: 0
Reputation: 29789
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.
Upvotes: 2