Reserve disk space before writing a file for efficiency

前端 未结 6 744
情书的邮戳
情书的邮戳 2020-12-14 19:42

I have noticed a huge performance hit in one of my projects when logging is enabled for the first time. But when the log file limit is reached and the program starts writing

6条回答
  •  佛祖请我去吃肉
    2020-12-14 20:01

    If you are using C++ 17, you should do it with std::filesystem::resize_file

    Link

    Changes the size of the regular file named by p as if by POSIX truncate: if the file size was previously larger than new_size, the remainder of the file is discarded. If the file was previously smaller than new_size, the file size is increased and the new area appears as if zero-filled.

    #include 
    #include 
    #include 
    #include 
    
    namespace fs = std::filesystem;
    
    int main()
    {
        fs::path p = fs::current_path() / "example.bin"; 
        std::ofstream(p).put('a');
        fs::resize_file(p, 1024*1024*1024); // resize to 1 G
    }
    

提交回复
热议问题