I want to create the file with particular name. If it already exists then I want to create another file with the name appended by some number.
For example, I want to create the file log.txt
but it is already there. Then I will create new file log1.txt
, log2.txt
, log3.txt
....
Is there any good way to record into the file duplication information?
Just check if the file exists, if yes, check for the next and so on, like in this code:
#include <sys/stat.h>
#include <iostream>
#include <fstream>
#include <string>
/**
* Check if a file exists
* @return true if and only if the file exists, false else
*/
bool fileExists(const std::string& file) {
struct stat buf;
return (stat(file.c_str(), &buf) == 0);
}
int main() {
// Base name for our file
std::string filename = "log.txt";
// If the file exists...
if(fileExists(filename)) {
int i = 1;
// construct the next filename
filename = "log" + std::to_string(i) + ".txt";
// and check again,
// until you find a filename that doesn't exist
while (fileExists(filename)) {
filename = "log" + std::to_string(++i) + ".txt";
}
}
// 'filename' now holds a name for a file that
// does not exist
// open the file
std::ofstream outfile(filename);
// write 'foo' inside the file
outfile << "foo\n";
// close the file
outfile.close();
return 0;
}
which will find a non-taken name and create a file with that name, write 'foo' into it and then will close the file, eventually.
I was inspired for the code from here.