Sign in to follow this  
BladeStone

If a file doesn't exist, don't make one

Recommended Posts

Using: std::ifstream file; file.open(name); Will make a file if it can't find it. How to do we look to see if the file exists with out creating one? We just want to look for it. I'm having no luck searing for "find file" or "existing file" or "don't open ifstream" or "look for file but don't open" Thank you in advance

Share this post


Link to post
Share on other sites
attributed to google :


fstream myfile;
myfile.open(<path_and_name>, ios::read);
if (myfile.is_open())
//the file is opened
else
//the file was not opened --> something happens!
myfile.close();

Share this post


Link to post
Share on other sites
Thank you thank you thank you!!!

tnutty: my compiler/gui (DevC++) said ios::read was not part of std::ios I don't know why.

Hollower: Perfect, exactly what I was looking for :)

Thank you both!

Share this post


Link to post
Share on other sites
Depending on what you're doing, you may want to look into Boost.Filesystem.

if (boost::filesystem::exists(filepath))
{ // do stuff }


I don't think I'd use it if this was the only reason, but it might be useful elsewhere, or in the future.

Share this post


Link to post
Share on other sites
Or instead of specifying that you want to open the file for input, you could just use a file that's only openable for input.

And instead of using a member function to initialize a variable, you could use its constructor.


void writeToFileOnlyIfItAlreadyExists(const std::string& filename) {
std::ifstream itExists(filename.c_str());
if (!itExists) { return; }

std::ofstream writeToIt(filename.c_str());
writeToIt << "OMG WHERE DID THE OLD DATA GO D:";
}

// Note that streams are automatically cleaned up in the destructor, so there
// is no need to .close() them explicitly, either.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this