开发者

Xcode iPhone: Removing text from a .txt file

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 s开发者_开发问答trings 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


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];


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜