如何在使用 fstream 打开文件时截断文件
How to truncate a file while it is open with fstream
我知道
可以用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 上交换。 我能想象到的最好的事情就是打开一个空文件并调用交换。 这不会是原子的,而是尽可能接近的。
相关文章:
- 使用fstream对txt文件中的数字进行循环
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- 使 std::fstream 写入文件末尾,但从头开始读取
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 如何检查文件是否已存在于 fstream C++中
- 使用 fstream 库并在屏幕上打印的文件有问题?
- Windows std::fstream 修改文件后打开()?
- 如何删除文件中的数字,通过 c++ fstream 的
- 如何使用单个fstream创建、读取和写入文件
- 如何使用fstream从.txt文件C++中取出int值
- fstream库,试图创建一个变量名为(c++)的文件
- 变量 std::fstream 文件具有初始值设定项,但类型不完整 编译错误
- 如何在 c++ 中使用 fstream 读取.txt文件
- 为什么错误"permission denied","id returned 1 exit status"仅在 IM 使用 C++ 中的头文件 fstream 时才出现
- 创建.dat文件 (fstream) c++
- 如何读取特定文件fstream
- 在驱动器c:中按类打开文件fstream类
- 使用库更新文件<fstream>(仅覆盖特定部分)
- 读取和写入同一个文件fstream