How to insert data to text file with using NSFileHandle

1.7k views Asked by At

My code replaces text instead of inserting it starting from 5 symbol:

NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath: filePath];
[file seekToFileOffset: 5];

[file writeData: [value dataUsingEncoding:NSUTF8StringEncoding]];

Is there any way to insert data to text file?

3

There are 3 answers

1
Jonathan Thurft On

That's because your code set the index position to 5 and start writing from there, thus replacing everything from 5 onwards.

I would copy the content of the file to a variable and modify it from there as a string. as by the looks of it what you attempt to do is not possible

Update: Given that what you need is to write from X offset this should do the trick

   NSFileHandle *file;
        NSMutableData *data;

        const char *bytestring = "black dog";

        data = [NSMutableData dataWithBytes:bytestring length:strlen(bytestring)];


        file = [NSFileHandle fileHandleForUpdatingAtPath: @"/tmp/quickfox.txt"];

        if (file == nil)
                NSLog(@"Failed to open file");


        [file seekToFileOffset: 10];

        [file writeData: data];

        [file closeFile];
0
Lucas Derraugh On

Well this might not be an efficient way, but you could read the entire text file into an NSMutableString and then use insertString:atIndex: and then write it back out. As far as I know there is no way to insert text into an existing file. Similar question

A quick example:

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

[contents insertString:@"Some string to insert" atIndex:5];
[contents writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
0
Johnson Mathew On

Inserting data somewhere in a sequential file would require that the entire file be rewritten. It is possible, however, to add data to the end of a file without rewriting the file.