-2
/tmp
パスに1000個の一時ファイルを作成する必要があります。以下は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;
}
}
}
注:作業完了後にファイルを削除しました。
誰かがこの方法が失敗する理由を説明し、存在する場合はより良いものを提案できますか?
は、あなたがしようとしているものは何でものために悪いデザインを示しています。何を達成しようとしていても、いくつかの一時ファイルを使用する方法を理解する必要があります。このようなものが本当に必要な場合は、一時ディレクトリを1つ作成し、それにすべての一時ファイルを作成します。 –
また、くぼみを固定してください。コードは他には読みにくいです。 – HolyBlackCat