Reputation: 2309
I want to overwrite the current data at the beginning of the my text file called data.txt (in my resources folder). There will always be only one line (no spaces or anything) and I want this line to be overwritten when appropriate. This is how I have been doing it so far but this only writes contents at the end of the file and doesn't begin from the beginning aka overwriting the line I need. If anyone can help me it would be appreciated. Thanks!
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//append filename to docs directory
NSString *myPath = [documentsDirectory stringByAppendingPathComponent:@"data.txt"];
fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:myPath];
writtenString= [[NSString alloc]initWithFormat:@"%d", message];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[writtenString dataUsingEncoding:NSUTF8StringEncoding]];
[writtenString release];
Upvotes: 1
Views: 2389
Reputation: 90521
Mike's answer will allow you to overwrite the contents of your file, but not in a nice line-oriented manner that you're imagining.
You can't adjust the internal contents of a file such that, if you insert stuff, the existing following data will be pushed later and, if you remove stuff, the existing following data will be pulled up to come right after the removal point.
You have two basic operations available: you can truncate a file at a certain length, possibly 0, discarding any old data past that point. And you can write data at a certain position. If there was already data at that position, it is overwritten (i.e. lost). If the byte range to which you're writing extends past the end of the file, the file is extended.
However, any of the old data which you neither truncated nor overwrote remains where it is. In no case is it moved.
So, if you want to change the first line of a text file, and if you can't be sure that the new line is exactly the same length as the old line, then you have to take care of moving everything from the second line on to its new location. One simple approach, suitable for small files, is to read the entire thing into memory, adjust it there, and write it all out again. Another is to iterate over the file, reading in chunks and then writing them out in their new locations. If you are moving data toward the start, you start at the beginning; if you are moving data toward the end, you start at the end.
Upvotes: 2
Reputation: 42795
This is how I have been doing it so far but this only writes contents at the end of the file and doesn't begin from the beginning aka overwriting the line I need.
Well, yeah, because you call:
[fileHandle seekToEndOfFile];
and it's doing what you asked. Try:
[fileHandle seekToFileOffset: 0];
Upvotes: 1