How to Clear File Content in C++

One common method to clear the contents of a file using file stream objects and related functions in C++ is as follows:

  1. Open the file and create an output file stream object.
std::ofstream ofs("file.txt", std::ios::trunc);

std::ios::trunc is used to open a file with truncation, which means emptying the file content.

  1. Close the stream object.
ofs.close();

This empties the content of the file.

bannerAds