overwrite an fstream object

J

John Smith

I would like to write over a file if it exists (or create one if
it doesn't exist). The following codes do nothing if the file
already exists. How do I get it to overwrite an existing file?

Also, if the existing file is longer than what's going to be
written, how do I erase the excess portion of the existing file?

fsF.open ("test.txt", ios::eek:ut|ios::trunc);
if (fsF.fail())
{
cout << "File test.txt cannot be opened.";
fsF.clear();
}

fsF << something

fsF.close();
 
M

Mike Wahler

John Smith said:
I would like to write over a file if it exists (or create one if
it doesn't exist). The following codes do nothing if the file
already exists. How do I get it to overwrite an existing file?

std::eek:fstream ofs("filename");

if(ofs)
std::cerr << "file created or truncated\n";
else
std::cerr << "failed to create or truncate file\n";
Also, if the existing file is longer than what's going to be
written, how do I erase the excess portion of the existing file?

See above.

-Mike
 
J

John Smith

Mike said:
std::eek:fstream ofs("filename");

if(ofs)
std::cerr << "file created or truncated\n";
else
std::cerr << "failed to create or truncate file\n";

Thanks. Changing from fstream to ofstream did the trick, but why?
 
M

Mike Wahler

John Smith said:
Thanks. Changing from fstream to ofstream did the trick, but why?

Read about the default parameters for the various fstream types.

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top