so I am developing an application, which requires to create a file, write into it, call another program with that file is an input, and delete the file.
I looked for possible solution and one solution looks like this.
std::FILE* tmpf = std::tmpfile();
std::fputs("Hello, world", tmpf);
According to the documentation of std::tmpfile
, if either the file is closed manually, or the program exits in natural way, the file will be deleted. This looks like good solution with one exception. It looks messy (using C I/O, instead of C++ streams).
Another solution would be to use std::tmpnam
, which will generate unique file name.
std::string file_name = std::tmpname(NULL);
// (*)
std::fstream stream{file_name};
stream << "Hello World" << std::endl;
But there is a problem with this one too. If another program creates file with the same name, while my program is in (*)
, we will both be doing operations on same file, which is certainly something I'd like to avoid.
C++ STL (still) does not support file system operations, like checking if file exists. I could use something like stat
to check that, but since checking for file and creating it is not atomic, it would not solve anything. And I did not find C++ STL method of atomic operation, which would: Check if file exists, if not, open it, if yes, fail.
So, my question is, what is the right way of solving this problem? Did I miss something?
Aucun commentaire:
Enregistrer un commentaire