iosobjective-cnsdatansfilehandle

Attach text at the beginning of the file


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

Solution

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