I am writing a program which downloads a file from a URL. Because the name of the downloaded file depends on the url, there is a risk of duplication if the user downloads the same file twice.
For example if the url is : http://www.example.org/myfile.zip The downloaded file name will be myfile.zip. and if the user downloads it again the name will be myfile(1).zip
To achieve this, I wrote the following code :
//A file already exist, we use the usual name
//but add a number before the extension like "Name(X).extension" X being a number
//Append the number just before the file extension
auto pos = name.find_last_of(".");
std::string nameWithoutExt = name.substr(0, pos);
std::string extension = name.substr(pos);
std::ostringstream possibleName;
int i = 1;
do
{
//Clear the string stream
possibleName.str("");
possibleName.clear();
possibleName<< nameWithoutExt << "(" << std::to_string(i) << ")" << extension;
++i;
//Check if a file with the possible name exists
} while (std::experimental::filesystem::exists(builder.str()));
name = builder.str();
This solution does not look optimal to me, because it may require a lot of calls to std::experimental::filesystem::exists
function. Are there any ways to improve this?
directory_iterator
to list every file in a path \$\endgroup\$name
already ends in (for example)(1).zip
? \$\endgroup\$