well i have made a .txt file (for save /reload blah blah ..) ..i want it blank before program runs ..how can i do it


- or is there any way i can create a new file every time overwriting the existing file

Codewise this mean you just open a File using std::ifstream::trunc

std::ifstream File;
std::string filepath = "text.txt";

File.open(filepath.c_str(), std::ifstream::out | std::ifstream::trunc );
if (!File.is_open() || File.fail())
{
   File.close();
   printf("\nError : failed to erase file content !");
}
File.close();

Codewise this mean you just open a File using std::ifstream::trunc

std::ifstream File;
std::string filepath = "text.txt";

File.open(filepath.c_str(), std::ifstream::out | std::ifstream::trunc );
if (!File.is_open() || File.fail())
{
   File.close();
   printf("\nError : failed to erase file content !");
}
File.close();

ifstream means file is opened for input so why would you truncate the file? File should be truncated when you want to write something to it right? (I am having a doubt pls clarify

Codewise this mean you just open a File using std::ifstream::trunc

std::ifstream File;
std::string filepath = "text.txt";

File.open(filepath.c_str(), std::ifstream::out | std::ifstream::trunc );
if (!File.is_open() || File.fail())
{
   File.close();
   printf("\nError : failed to erase file content !");
}
File.close();

Thanks For Sharing but i have doubt its working properly or Error in If condition.

If you don't believe us, then write the program and remove all doubts.

The easiest way to alleviate doubts is to try it and see what happens.

@v3ga
@dofdiamond

Works for either input or output purpose.
I used ifstream since learner guy wanted the file to be cleared at startup.
This can pretend writing something in the file, before you actually use it.

Of course it's pointless truncating a file when you actually want to see whats inside.
But in case he only wants to empty it(without seeing in the file or writing in it), then it doesn't really matter which one you use.

This article has been dead for over six months. Start a new discussion instead.