简体   繁体   中英

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". I want to delete "world" (like pressing Backspace in a text editor), then save the file. 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/ .

It seems to me that files and streams therefore are NOT like arrays: I can't just delete a byte from a file? 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". 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.

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.That's the easy and fast way (see http://man7.org/linux/man-pages/man2/mmap.2.html )

Assume your original file is "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. Upon writing data, replace the original file with the new one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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