我知道可以截断一个文件
std::fstream fs(mypath, std::fstream::out | std::fstream::trunc);
Run Code Online (Sandbox Code Playgroud)
但我需要读取文件,截断它,然后用相同的文件句柄写所有内容(所以整个操作是原子的).任何人?
我不认为您可以进行"原子"操作,但使用现在已被接受为标准库(C++ 17)一部分的文件系统技术规范,您可以像这样调整文件大小:
#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";
}
Run Code Online (Sandbox Code Playgroud)