简体   繁体   English

如何使用NSFileHandle将数据插入文本文件

[英]How to insert data to text file with using NSFileHandle

My code replaces text instead of inserting it starting from 5 symbol: 我的代码替换了文本,而不是从5个符号开始插入文本:

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

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

Is there any way to insert data to text file? 有什么方法可以将数据插入文本文件?

That's because your code set the index position to 5 and start writing from there, thus replacing everything from 5 onwards. 那是因为您的代码将索引position to 5并从那里开始写入,从而从5开始替换了所有内容。

I would copy the content of the file to a variable and modify it from there as a string . 我会将文件的内容复制到一个变量,然后从那里将其修改为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 更新:鉴于您需要从X偏移量写入内容,因此应该可以解决问题

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

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. 好吧,这可能不是一种有效的方法,但是您可以将整个文本文件读取到NSMutableString中,然后使用insertString:atIndex:然后将其写回。 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];

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. 但是,可以在不重写文件的情况下将数据添加到文件的末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM