将内容添加到文件中间......直到最后都没有阅读 [英] Adding content to middle of file..without reading it till the end

查看:27
本文介绍了将内容添加到文件中间......直到最后都没有阅读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 unix.stackexchange 上阅读了有关如何在无需创建临时文件的情况下在文件中添加或删除行的各种问题/答案.

I have read various questions/answers here on unix.stackexchange on how to add or remove lines to/from a file without needing to create a temporary file.

https://unix.stackexchange.com/questions/11067/is-there-a-way-to-modify-a-file-in-place?lq=1

似乎所有这些答案都需要一个人至少阅读到文件末尾,如果输入是一个大文件,这可能会很耗时.有没有解决的办法?我希望文件系统能够像链表一样实现……所以应该有一种方法可以到达所需的行",然后只需添加内容(链表中的节点).我该怎么做?

It appears all these answers need one to atleast read till end of the file, which can be time consuming if input is a large file. Is there a way around this? I would expect a file system to be implemented like a linked list...so there should be a way to reach the required "lines" and then just add stuff (node in linked lists). How do I go about doing this?

我的想法正确吗?或者我错过了什么?

Am I correct in thinking so? Or Am I missing anything?

Ps:我需要在'C'中完成这个并且不能使用任何shell命令.

Ps: I need this to be done in 'C' and cannot use any shell commands.

推荐答案

您可以就地修改文件,例如使用 dd.

You can modify a file in place, for example using dd.

$ echo Hello world, how are you today? > helloworld.txt
$ cat helloworld.txt
Hello world, how are you today?
$ echo -n Earth | dd of=helloworld.txt conv=notrunc bs=1 seek=6
$ cat helloworld.txt
Hello Earth, how are you today?

问题在于,如果您的更改也更改了长度,则无法正常工作:

The problem is that if your change also changes the length, it will not quite work correctly:

$ echo -n Joe | dd of=helloworld.txt conv=notrunc bs=1 seek=6
Hello Joeth, how are you today?
$ echo -n Santa Claus | dd of=helloworld.txt conv=notrunc bs=1 seek=6
Hello Santa Clausare you today?

当您更改长度时,您必须重新写入文件,如果不完全,则从您所做的更改点开始.

When you change the length, you have to re-write the file, if not completely then starting at the point of change you make.

在 C 中,这与 dd 相同.你打开文件,寻找,然后写.

In C this is the same as with dd. You open the file, you seek, and you write.

这篇关于将内容添加到文件中间......直到最后都没有阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆