简体   繁体   English

如何从 C 或 C++ 中的文件中删除字节?

[英]How do I delete bytes from a file in C or C++?

I've been Googling this for hours...reading and reading and reading, and yet nothing I come across seems to answer this simple question: In C or C++ programming: I have a file, it contains "hello world".我已经在谷歌上搜索了几个小时......阅读和阅读和阅读,但我遇到的任何问题似乎都无法回答这个简单的问题:在 C 或 C++ 编程中:我有一个文件,它包含“hello world”。 I want to delete "world" (like pressing Backspace in a text editor), then save the file.我想删除“世界”(比如在文本编辑器中按Backspace ),然后保存文件。 How do I do this?我该怎么做呢?

I know that files are streams ( excellent info on that here! ), which don't seem to have a way to delete items from a file per say, and I've studied all of the file-related functions in stdio.h: http://www.cplusplus.com/reference/cstdio/fopen/ .我知道文件是这里有很好的信息! ),它似乎没有办法从文件中删除项目,而且我已经研究了 stdio.h 中所有与文件相关的函数: http://www.cplusplus.com/reference/cstdio/fopen/

It seems to me that files and streams therefore are NOT like arrays: I can't just delete a byte from a file?在我看来,文件和流因此不像 arrays:我不能只从文件中删除一个字节? Rather (I guess?) I have to create an entire new file and copy the whole original file into the new file withOUT the parts I want to delete?而是(我猜?)我必须创建一个全新的文件并将整个原始文件复制到新文件中,而不需要删除我想要删除的部分? Is that the case?是这样吗?

The only other option I can think of is to seek to the position before "world", then write binary zeros to the end of the file, thereby overwriting "world".我能想到的唯一其他选择是在“世界”之前寻找 position,然后将二进制零写入文件末尾,从而覆盖“世界”。 The problem with this, however, is a text editor will now no longer properly display this file, as it has non-printable characters in it--and the file size hasn't shrunk--it still contains these bytes--it's just that they hold zeros now instead of ASCII text, so this doesn't seem to be right either.然而,这个问题是文本编辑器现在将不再正确显示该文件,因为其中包含不可打印的字符 - 并且文件大小没有缩小 - 它仍然包含这些字节 - 它只是他们现在持有零而不是ASCII文本,所以这似乎也不正确。

Related有关的

You can use a memory map from the source file and copy the data blocks you want to another memory map over target file.您可以使用源文件中的 memory map 并将您想要的数据块复制到另一个 memory Z1D78DC8ED51214E5AEB2 上的目标文件That's the easy and fast way (see http://man7.org/linux/man-pages/man2/mmap.2.html )这是简单快捷的方法(参见http://man7.org/linux/man-pages/man2/mmap.2.html

Assume your original file is "data.txt".假设您的原始文件是“data.txt”。 As part of your code, open a new temp file say "data.txt.tmp" and start writing contents to it from original file.作为代码的一部分,打开一个新的临时文件,例如“data.txt.tmp”并开始从原始文件向其中写入内容。 Upon writing data, replace the original file with the new one.写入数据后,将原始文件替换为新文件。

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

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