C ++如何高效更新文件内容

时间:2019-05-20 10:40:31

标签: c++ file filesystems fstream ofstream

我想知道如何更新文件中的值?假设我有这样的东西:

 //thread 1:    
       std::vector<int> v(10);

 //v is changed i.e. to {0,0,0,0,0,2,0,0,0,0}
       ...

 //after some time v is changed agian to: i.e. {0,0,3,0,0,2,0,0,0,0}

 //etc

 //thread 2: (is a react thread)   
 //apart from synchronization

       std::fstream file;
       file.open("test.txt", std::ios_base::out);
       while(true)
       {
           //file.seekp(0, std::ios_base::beg); -> with this almost works, but update takes too long
           for (auto const& e : v)
               file << e << ',';
           file.flush();
       }

由于在每次迭代中打开和关闭文件都是非启动程序,因此我想一次打开文件,然后只更新文件中的值,但是在第一次迭代后不更新文件。

1 个答案:

答案 0 :(得分:0)

可以通过使用std::call_oncestd::once_flag

#include <mutex>
std::once_flag flag;

//in thread 2
std::call_once(flag, file.open("test.txt", std::ios_base::out));

file.open()仅被调用一次。