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

后端 未结 4 1381
醉梦人生
醉梦人生 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:34

    I've done this function:

    #include 
    #include 
    #include 
    #include 
    
    std::string open_temp(std::string path, std::ofstream& f) {
        path += "/XXXXXX";
        std::vector dst_path(path.begin(), path.end());
        dst_path.push_back('\0');
    
        int fd = mkstemp(&dst_path[0]);
        if(fd != -1) {
            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;
        open_temp("/tmp", logfile);
        if(logfile.is_open()) {
            logfile << "hello, dude" << std::endl;
        }
    }
    

    You should probably make sure to call umask with a proper file creation mask (I would prefer 0600)- the manpage for mkstemp says that the file mode creation mask is not standardized. It uses the fact that mkstemp modifies its argument to the filename that it uses. So, we open it and close the file it opened (so, to not have it opened twice), being left with a ofstream that is connected to that file.

提交回复
热议问题