Read and write to file in Cocoa

GigaRoc

Registered
hello,
i have 5 int's i would like to write to a file and then read from again.
I've looked around on the web and there doesn't seem to be a lot of info on this
is there a simple way to do this?

Giga
 
Code:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
    //the int values
    int values[5] = {
        5,
        4,
        3,
        2,
        1
    };
    int i;
    NSError *error;
    
    //store them into a file
    NSMutableString *mutstr = [[NSMutableString alloc] init];
    for(i = 0; i < 5; i++)
        [mutstr appendFormat:@"%i ", values[i]];
    
    //write to file
    [mutstr writeToFile:@"Data.txt" atomically:YES encoding:NSUnicodeStringEncoding error:&error];
    
    //read from the file
    NSString *string = [[NSString alloc] initWithContentsOfFile:@"Data.txt"];
    if(string == nil)
    {
        NSLog(@"Error reading file");
        return 1;
    }
    
    //scan the integers from the file
    NSScanner *scanner = [[NSScanner alloc] initWithString:string];
    while([scanner isAtEnd] == NO)
    {
        NSInteger integer;
        [scanner scanInt:&integer];
        NSLog(@"Value : %d", integer);
    }
    
    [pool drain];
    return 0;
}
 
Hello, I'm new here. I registered because I have 2 questions about this:

1. What are the possible reasons for the writeToFile:atomically:encoding: method to fail and return NO?
2. In your example you did not specify a path for Data.txt. In which folder will this file be saved?

Thanks in advance.
 
Back
Top