Reputation: 2549
I try to handle the cases when I try to write a file that already exists by adding plus ID to the filename. In short it's something like what Windows does when I copy a file.
Assuming I have a file test.bmp. I want to apply a filter on it and save the filtered image as testout.bmp. But the testout.bmp already exists in that folder, so the program catches this and save it as testout(1).bmp for example. In my code I try to use exeptions. My idea is something like this: (pseudo code)
bool IMAGE_DATA::openFile(const char* filename)
{
int i = 0;
try
{
if(file_exists(filename)) throw whatever;
}
catch(type whatever)
{
changefilename(filename,i)
i++;
if(file_exists(filename)) /* throw whatever/do something */;
}
};
Currently if the file already exists, my program only exists (file_exists just returns true when there's a file with that name in the folder).
I started to redesign my base function with exception handling instead of simply returning false if any error occurred. I wrote whatever here because I will have more throws (if if the file cannot be opened or exists but the same as my file ect.).
How can I try and catch file names until there's a file name that's correct. Or is there any easier method for this and I should not use exceptions? What is the best design to handle this problem?
Upvotes: 0
Views: 578
Reputation:
In your scenario, having an existing file is no exception. Hence, do not use them. If you are trying pass additional information around you may use a functor:
#include <iostream>
struct FileExits {
bool value;
std::string information;
FileExits(const std::string& name)
: value(true), information("Test")
{}
operator bool () const { return value; }
};
int main() {
// Endless loop in this example
std::string name;
while(FileExits result = name) {
std::cout << result.information << std::endl;
}
// ...
return 0;
}
Upvotes: 1
Reputation:
I can't quite grasp why you would use exceptions for this. Exceptions as flow control is considered very poor style, apart from some very specific idioms. Throwing and catching anything that isn't derived from std::exception is also a no-no. Plus, your posted code isn't even close to compiling, so my answer is also in pseudo-code. One more thing, why use char* for the name and not std::string?
Would this do what you required?
bool IMAGE_DATA::openFile(std::string filename)
{
while(file_exists(filename))
{
filename = add_1_to_filename(filename);
}
open(filename);
}
Upvotes: 2