0

I am trying to add some text at the beginning of my text file. I am currently trying to create NSFileHandle and seek to fileOffset, but it overwrites my data (as expected).

How can I add it at the beginning?

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString* eegFileName = [NSString stringWithFormat:@"%@/%@", documentsDirectory, self.EEGFileName];

NSString* content = [NSString stringWithFormat:@"numberOfSamples: %d", numberOfSamples];

NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:eegFileName];
[myHandle seekToFileOffset:0];
[myHandle writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
Cœur
  • 37,241
  • 25
  • 195
  • 267
izik461
  • 1,131
  • 12
  • 32
  • It seems that you need to make a copy of your content file before (to a `NSString`), then combine append it to the new content to add at the begining, then write the file: http://stackoverflow.com/questions/18084853/how-to-insert-data-to-text-file-with-using-nsfilehandle – Larme Nov 23 '15 at 12:40
  • Yup, I've already found this. Not fast, nor elegant, but works. – izik461 Nov 23 '15 at 12:44
  • Indeed, but according to a question linked in the previous one, it's the only way: http://stackoverflow.com/questions/4593418/inserting-a-string-at-a-specified-line-in-text-file-using-objective-c – Larme Nov 23 '15 at 12:45

1 Answers1

1

I've found not an elegant and fast, but still a solution.

NSString *path = //Your file
NSMutableString *contents = [NSMutableString stringWithContentsOfFile:txtFilePath encoding:NSUTF8StringEncoding error:NULL];

[contents insertString:@"Some string to insert" atIndex:0];
[contents writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
izik461
  • 1,131
  • 12
  • 32