If a file doesn't exist, don't make one
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
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();
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!
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!
Depending on what you're doing, you may want to look into Boost.Filesystem.
I don't think I'd use it if this was the only reason, but it might be useful elsewhere, or in the future.
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.
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.
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
Popular Topics
Advertisement