How do I clear a .txt file in c++ using fstream? I'm trying to clear my txt file at a certain point in my code. How would I go about doing that?
Asked
Active
Viewed 270 times
0
-
2Delete it and recreate when/if required? – Martin James Mar 31 '21 at 04:55
-
Does this answer your question? [How to truncate a file while it is open with fstream](https://stackoverflow.com/questions/20809113/how-to-truncate-a-file-while-it-is-open-with-fstream) – Theraot Mar 31 '21 at 04:58
-
Do you want to truncate the file, or to replace every line with a blank one? Please give an example of clearing the file. Or do you want to ``remove` that file. The answer could be operating system specific. For Linux, see also [syscalls(2)](https://man7.org/linux/man-pages/man2/syscalls.2.html) – Basile Starynkevitch Mar 31 '21 at 05:00
-
Simply [remove it](https://en.cppreference.com/w/cpp/filesystem/remove), then create a new file. – Andreas Mar 31 '21 at 05:15
1 Answers
1
You can use this code snippet:
std::fstream f;
f.open("path_to_file", std::ofstream::out|std::ofstream::trunc);
f.flush();
f.close();

Navid_pdp11
- 3,487
- 3
- 37
- 65