-2

パスに 1000 個の一時ファイルを作成する必要があり/tmpます。以下は、mkstemp (競合状態から安全) を使用した私のアプローチですが、ファイルの作成は 500 に制限されており、残りは失敗しました。

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;
        }
    }
}

注:作業が完了したらファイルを削除しました。

誰かがこのアプローチが失敗する理由を説明し、もしあればより良いアプローチを提案できますか?

4

1 に答える 1