I am trying to learn how to handle and work on files, now I know how to open them, write on them and read. What I would like to do is, how can I delete data/content from the file, when I have finished to use the program? I use the a txt file to save some informations that I used them, when I need during the execution of the program, but when I finish, I would like to delete the data saved, which are simply numbers. I was thinking to remove the file each time, and to create, but I think it's not the ideal. Any suggestions?
-
Possible duplicate of [How to clear the content of a file after it is opened using fstream?](https://stackoverflow.com/questions/24189029/how-to-clear-the-content-of-a-file-after-it-is-opened-using-fstream) – samini Sep 18 '19 at 10:09
4 Answers
Using std::filesystem::resize_file
:
std::filesystem::resize_file(your_file, 0);

- 62,093
- 7
- 131
- 191
In such a case, you usually just re-write the file as a whole. If it is a small file, you can read in the entire content, modify the content and write the file back.
With large files, if you fear that you are consuming too much memory, you can read in the file in chunks of appropriate size, but you'd write these chunks to another, temporary file. When being finished, you delete the old file and move the temporary file to the location of the old file.
You can combine both aproaches, too: Read the entire file, write it to temporary at once, then delete and move; if anything goes wrong while writing the temporary, you'd still have the old file as backup...

- 24,880
- 4
- 34
- 59
-
2"junks" -> "chunks" - unless you're evaluating the quality of the stored data :) – Quentin Sep 18 '19 at 10:11
You can open the file in writing mode (w) and then close it . It will truncate all previous data.

- 322
- 3
- 13
It's generally a good idea to clean up temporary files once your program ends. I certainly wouldn't leave an empty temporary file hanging around. You can easily remove file (e.g. with boost::filesystem::remove
or std::filesystem::remove
). If you really just want to 'clear' a file then:
void clear_file(const std::string& filename)
{
std::ofstream file {filename};
}
Will do the job.

- 8,179
- 6
- 31
- 56