Frustrated Coder
Frustrated Coder

Reputation: 4687

how to delete contents of a file from main body of c++

I wanted to know if I can delete the values (string or int) written in a file from main. i.e. erase entire data in a text file and make it empty like before If yes, how?

Upvotes: 0

Views: 4876

Answers (2)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361352

You can use ios_base::trunc openmode with ofstream:

(truncate) Any current content is discarded, assuming a length of zero on opening.

Example,

std::ofstream ofile("filename.txt", ios_base::trunc);

//work with ofile

ofile.close();

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272477

Just overwrite it with a new, empty file:

#include <fstream>

std::ofstream ofs("myfile.txt");
ofs.close();

Upvotes: 4

Related Questions