Reading and Writing



Example:

   //Method reads a string from a text file in the docs folder
-(NSArray *) readLinesFromLocalFileDoc:(NSString *) filename {
   //get the documents directory:
   NSArray *paths = NSSearchPathForDirectoriesInDomains
   (NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];

   //make a file name to read the data from the documents directory:
   NSString *path = [NSString stringWithFormat:@"%@/%@",
       documentsDirectory,filename];
   NSError *error;
   NSArray *lines;
   lines = [[NSString stringWithContentsOfFile:path
       encoding:NSASCIIStringEncoding
       error:&error]componentsSeparatedByString:@"\n"];
   if (lines != nil)
     [lines retain];
   //NSLog(@"end of readLines");
   return lines;
}



// reads a text file from the bundle (note: you can't write to the bundle)
-(NSArray *) readLinesFromBundleTXTFile:(NSString *) filename {
   NSArray *lines;
   NSError *error;

   NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"txt"];
   lines = [[NSString stringWithContentsOfFile:path
       encoding:NSASCIIStringEncoding
       error:&error]componentsSeparatedByString:@"\n"];
   return lines;
}



-(NSString *) stringWithoutSpecialCharacters:(NSString*) inString
{
   NSString *newString = @"";
   for (int i=0; i<[inString length]; i++)
   {
     if ([inString characterAtIndex:i] >31)
       newString = [newString stringByAppendingFormat:@"%c",[inString characterAtIndex:i]];
   }
   return newString;
}



-(NSString *) stringWithoutSpecialCharactersExceptNewLines:(NSString*) inString
{
   NSString *newString = @"";
   for (int i=0; i<[inString length]; i++)
   {
     if ([inString characterAtIndex:i] >31 && [inString characterAtIndex:i] < 127)
         newString = [newString stringByAppendingFormat:@"%c",[inString characterAtIndex:i]];
     else if ([inString characterAtIndex:i] == 10)
         newString = [newString stringByAppendingFormat:@"\n"];
   }
   return newString;
}



//Method writes a string to a text file (docs folder)
-(BOOL) writeToDocsTextFile:(NSString *) content filename:(NSString *) filename {
   //get the documents directory:
   NSArray *paths = NSSearchPathForDirectoriesInDomains
       (NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];

   //make a file name to write the data to using the documents directory:
   NSString *fileNameWithPath = [NSString stringWithFormat:@"%@/%@",
       documentsDirectory,filename];
   //save content to the documents directory
   return [content writeToFile:fileNameWithPath
       atomically:YES
       encoding:NSASCIIStringEncoding
       error:nil];
}