1

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

Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265
  • 1
    *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?* As far as I know, yes. – R Sahu Oct 22 '19 at 04:51
  • "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?" No. You can keep it in memory, change it, and just overwrite the old one. I don't suspect that is much better, though. –  Oct 22 '19 at 04:54
  • If I want to write EOF chars in the file to force a text editor to quit displaying data at that point, what do I use? `-1`? Ctrl + Z char (Dec 26)? – Gabriel Staples Oct 22 '19 at 06:54

3 Answers3

1

You want std::filesystem::resize_file()

Sid S
  • 6,037
  • 2
  • 18
  • 24
1

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.

Pavan
  • 11
  • 3
0

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)