Skip to main content
GameDev.net gamedev.net
🔒 Locked

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

Started by BladeStone Jun 10, 2009 at 10:24 PM 5 replies 1k views
Original Post
BladeStone
BladeStone
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
BladeStoneOwner, WolfCrown.com
tnutty
tnutty
attributed to google :

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

Our whole life is a opengl application.
Hollower
Hollower
std::ifstream file;file.open(name, ios::in);if ( file.fail() ) {    // file doesn't exist}
BladeStone
BladeStone
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!
BladeStoneOwner, WolfCrown.com
Denzin
Denzin
what they said
+ drop dev cpp
http://www.jasonbadams.net/20081218/why-you-shouldnt-use-dev-c/
TheUnbeliever
TheUnbeliever
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.
[TheUnbeliever]
Zahlman
Zahlman
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.