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

Ell*_*ron 10 c++ fstream std

我知道可以截断一个文件

std::fstream fs(mypath, std::fstream::out | std::fstream::trunc);
Run Code Online (Sandbox Code Playgroud)

但我需要读取文件,截断它,然后用相同的文件句柄写所有内容(所以整个操作是原子的).任何人?

Gal*_*lik 8

我不认为您可以进行"原子"操作,但使用现在已被接受为标准库(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)


Die*_*ühl 6

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