Next: 2 NSArray Up: 1 NSString Previous: 1.5 NSMutableString

1.6 Reading and Saving Strings to/from Files

We don't have the time to describe all the string-related features of the GNUstep base library; but it's useful to have at least a quick look at how easy is writing/reading strings to/from files.

If you need to write the contents of a string into a file, you can use the method -writeToFile:atomically:, as shown in the following example:

#include <Foundation/Foundation.h>

int
main (void)
{
  NSAutoreleasePool *pool = [NSAutoreleasePool new];
  NSString *name = @"This string was created by GNUstep";

  if ([name writeToFile: @"/home/nico/testing" atomically: YES])
    {
      NSLog (@"Success");
    }
  else 
    {
      NSLog (@"Failure");
    }
  return 0;
}
writeToFile:atomically returns YES upon success, and NO upon failure. If the atomically flag is YES, then the library first writes the string into a file with a temporary name, and, when the writing has been successfully done, renames the file to the specified filename. This prevents erasing the previous version of filename unless writing has been successful. Usually, this is a very good feature, which you want to enable.

Reading the contents of a file into a string is easy too. You can simply use +stringWithContentsOfFile:, as in the following example, which reads @"/home/nicola/test":

#include <Foundation/Foundation.h>

int
main (void)
{
  NSAutoreleasePool *pool = [NSAutoreleasePool new];
  NSString *string;
  NSString *filename = @"/home/nico/test";

  string = [NSString stringWithContentsOfFile: filename];
  if (string == nil)
    {
      NSLog (@"Problem reading file %@", filename);
      // <missing code: do something to manage the error...>
      // <exit perhaps ?>
    }

  /*
   * <missing code: do something with string...>
   */

  return 0;
}



2008-01-16