Jump to content
  • Advertisement
Sign in to follow this  
BladeStone

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

This topic is 3327 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
what they said
+ drop dev cpp
http://www.jasonbadams.net/20081218/why-you-shouldnt-use-dev-c/

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!