File input/output: Difference between revisions

Content added Content deleted
(Added Toka)
(Idiomatic example.)
Line 595: Line 595:
[[Category:GNU Compiler Collection]]
[[Category:GNU Compiler Collection]]


Many objects know how to create an instance from a file or write an instance to file. In this example, a dictionary write itself to a file using XML property list format, and then read back into a new instance.
There are various classes in Objective C for opening, reading, and writing files. One way is with the NSFileManager class for reading, and a NSFileHandle for writing.


NSDictionary *info = [NSDicionary dictionaryWithObjectsAndKeys:
NSString *inputPath = @"input.txt";
@"name", @"Joe",
NSString *outputPath = @"output.txt";
@"age", [NSNumber numberWithUnsignedInt:37],
nil];
if( [[NSFileManager defaultManager] isReadableFileAtPath:inputPath] ){
NSData *data = [[NSFileManager defaultManager] contentsAtPath:inputPath];
[info writeToFile:@"/tmp/test.plist" atomically:YES];
[[NSFileManager defaultManager] createFileAtPath:outputPath contents:data attributes:nil];
NSDictionary *saved = [NSDictionary dictionaryWithContentsOfFile:@"/tmp/test.plist"];
} else {

NSLog( @"No such file." );
There are many other methods to read and write files, accessing file attributes etc.
}


==[[Perl]]==
==[[Perl]]==