How to insert data to text file with using NSFileHandle

点点圈 提交于 2019-12-11 16:45:47

问题


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?


回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/18084853/how-to-insert-data-to-text-file-with-using-nsfilehandle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!