我知道可以使用截断文件的方法。
std::fstream fs(mypath, std::fstream::out | std::fstream::trunc);
但我需要读取文件、截断它,然后使用同一个文件句柄写入新内容(以便整个操作是原子的)。有人能帮忙吗?
#include <fstream>
#include <sstream>
#include <iostream>
#include <experimental/filesystem> // compilers that support the TS
// #include <filesystem> // C++17 compilers
// for readability
namespace fs = std::experimental::filesystem;
int main(int, char*[])
{
fs::path filename = "test.txt";
std::fstream file(filename);
if(!file)
{
std::cerr << "Error opening file: " << filename << '\n';
return EXIT_FAILURE;
}
// display current contents
std::stringstream ss;
ss << file.rdbuf();
std::cout << ss.str() << '\n';
// truncate file
fs::resize_file(filename, 0);
file.seekp(0);
// write new stuff
file << "new data";
}
文件流在打开文件时支持截断,但在其他操作时不支持。此外,这些操作也不会是“原子性”的:至少,在POSIX系统上,你可以愉快地读写已经被另一个进程打开的文件。
C++ 11 支持在 ofstream 上进行交换。我能想到的最好的方法是打开一个空文件并调用 swap。这不是原子操作,但已经尽可能接近了。