How to create a std::ofstream to a temp file?

后端 未结 4 1362
醉梦人生
醉梦人生 2020-12-24 12:45

Okay, mkstemp is the preferred way to create a temp file in POSIX.

But it opens the file and returns an int, which is a file descriptor. F

4条回答
  •  醉梦人生
    2020-12-24 13:16

    I think this should work:

        char *tmpname = strdup("/tmp/tmpfileXXXXXX");
        ofstream f;
        int fd = mkstemp(tmpname);
        f.attach(fd);
    

    EDIT: Well, this might not be portable. If you can't use attach and can't create a ofstream directly from a file descriptor, then you have to do this:

    char *tmpname = strdup("/tmp/tmpfileXXXXXX");
    mkstemp(tmpname);
    ofstream f(tmpname);
    

    As mkstemp already creates the file for you, race condition should not be a problem here.

提交回复
热议问题