views:

66

answers:

3

Hi, I have a text file with some strings in it, I am able to access the text from the file by using [NSString initWithContentsOfFile] function but what I want to do next is remove the whole text from that file but leaving the text file there as my application will continue to feed strings of message into the file. I've looked through NSString, NSStream, NSScanner, NSFileManager, NSHandle but still have no idea how to do it.

I can do a remove file function but I don't really want to do it because my application would be required to loop thousand over times and I think its unwise to continously delete and create a file.

Any idea? thanks

A: 

Remove content from a file is to write whole file again.

adf88
+1  A: 

You don't have to remove contents from file. When you will ready to put new information into file - you will just overwrite your old file.

NSString *str = @"test string";
NSError * error = nil;
[str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error)
    NSLog(@"err %@", [error localizedDescription]);

When you are appending additional data:

NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:appFile];
[myHandle seekToEndOfFile];
[myHandle writeData:data];
[myHandle closeFile];
mOlind
Great thanks, thats a simple code that I overlooked.
A: 

Have you considered using NSPipe instead? It sounds like you are trying to implement a queue of strings that need to be processed. There are many ways to do this. Not sure that thrashing the file system is the best approach given other options like NSOperationQueue, NSNotificationCenter. You can also use NSMutableArray like a queue using addObject: to push and removeObjectAtIndex: to pop strings. If you need to save unprocessed strings, it is very easy to save the array to a file as part of your suspend/terminate handling and reload on startup

falconcreek
OK, I will check that out too, thanks for your help