如何在使用 fstream 打开文件时截断文件

How to truncate a file while it is open with fstream

本文关键字:文件 fstream      更新时间:2023-10-16

我知道

可以用
std::fstream fs(mypath, std::fstream::out | std::fstream::trunc);

但我需要读取文件,截断它,然后使用相同的文件句柄写入新内容(因此整个操作是原子的)。任何人?

我认为您无法获得"原子"操作,但是使用现已被接受为标准库(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";
}

文件流不支持截断,除非在打开文件时。此外,这些操作无论如何都不会是"原子的":至少,在POSIX系统上,您可以愉快地读取和写入已被另一个进程打开的文件。

C++ 11 支持在 Ofstream 上交换。 我能想象到的最好的事情就是打开一个空文件并调用交换。 这不会是原子的,而是尽可能接近的。