Checking the existence of a file

S

smilesonisamal

Hi all,
I have a output file which is generated by a tool. I want to check
whether the file exists or not. If exists then delete it and invoke
the tool. Which one will be suitable for this case ifstream or
ofstream to open the file?

ifstream in;
in.open(xxx,std::ios::in);

if (in)
{
in.close();
in.clear();
remove(xxx);
.}
 
V

Victor Bazarov

I have a output file which is generated by a tool. I want to check
whether the file exists or not. If exists then delete it and invoke
the tool. Which one will be suitable for this case ifstream or
ofstream to open the file?

ifstream in;
in.open(xxx,std::ios::in);

if (in)
{
in.close();
in.clear();
remove(xxx);
.}

The best way would be to use your OS interface for actually checking the
existence of the file. Of course for a file to exist it has to be
readable, so if you don't want to be OS-specific, use 'ifstream'.

V
 
J

James Kanze

I have a output file which is generated by a tool. I want to
check whether the file exists or not. If exists then delete it
and invoke the tool. Which one will be suitable for this case
ifstream or ofstream to open the file?

What do you do if the file doesn't exist, invoke the tool
immediately? If so, the simplest answer would be to just delete
it, ignoring any error on the delete.
ifstream in;
in.open(xxx,std::ios::in);

if (in)
{
in.close();
in.clear();
remove(xxx);
}

That should work as well, except for the cases where it doesn't.
(If the file exists, but belongs to someone else, and you don't
have access rights to it, you probably can't do anything about
it.)
 

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,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top