-2

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?

Bob__
  • 12,361
  • 3
  • 28
  • 42
rosti
  • 1
  • 4
  • 2
    Even though having six randomly-generated characters in a temp filename should be enough for 500 temporary files, needing so many temporary files indicates a bad design for whatever you're trying to do. Whatever you're trying to accomplish, you need to figure out how to use a couple of temp files, at most. If you truly need something like this, create one temporary directory, and create all the temp files in it, yourself. – Sam Varshavchik Jun 25 '17 at 13:48
  • 1
    Also, please fix the indentation. The code is hard to read otherwise. – HolyBlackCat Jun 25 '17 at 13:51

1 Answers1

1
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?

Jay
  • 3,640
  • 12
  • 17