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

Started by
5 comments, last by Zahlman 14 years, 10 months ago
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
Advertisement
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.
std::ifstream file;file.open(name, ios::in);if ( file.fail() ) {    // file doesn't exist}
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
what they said
+ drop dev cpp
http://www.jasonbadams.net/20081218/why-you-shouldnt-use-dev-c/
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]
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.

This topic is closed to new replies.

Advertisement