I need to created 1000 temp files in /tmp
path. Below is my approach using mkstemp (safe from race conditon), but the file creation is limited to 500 only, the rest failed.
std::string open_temp(std::string path, std::ofstream& f) {
path += "/preXXXXXX";
std::vector<char> dst_path(path.begin(), path.end());
dst_path.push_back('\0');
int fd = mkstemp(&dst_path[0]);
if(fd != -1) { //fail condition
std::cout<<"not created count = "<<j++<<std::endl;
// j = 500 why fail it gloabl varibale?
path.assign(dst_path.begin(), dst_path.end() - 1);
f.open(path.c_str(),
std::ios_base::trunc | std::ios_base::out);
close(fd);
}
return path;
}
int main() {
std::ofstream logfile;
for(int i=0;i<1000;i++)
{
std::cout<<"count = "<<i++ <<std::endl;
open_temp("/tmp", logfile);
// ^^^ calling 1000 times but only 500 sucess which is that?
if(logfile.is_open()) {
logfile << "testing" << std::endl;
}
}
}
Note : I removed files after work done.
Can someone explain why this approach fails and suggest a better one if there is any?
std::cout<<"count = "<<i++ <<std::endl;
^^^
You're incrementing i
there additionally to the for
loop.
As a result i goes from 0 to 2, 4, 6, 8 etc. and the loop only runs 500 times.
Change it to std::cout<<"count = "<<i <<std::endl;
and see how that goes...
Also I see you're also doing j++
above, but I don't see where j
is defined?