gpt4 book ai didi

c++ - 如何在文件仍处于打开状态时删除文本文件的内容(无需重新打开文件)?

转载 作者:行者123 更新时间:2023-11-28 04:03:19 32 4
gpt4 key购买 nike

我只想打开一个文本文件一次。假设我打开一个文本文件,我要求用户输入一些内容,然后我将其写入文本文件。然后,用户想要修改一些东西,需要重写文件中的所有内容。如何在不关闭文件并重新打开文件的情况下实现这一点?

最佳答案

自 C++17 起可用 std::filesystem::resize_file()

namespace fs = std::filesystem;
fs::path p = fs::current_path() / "inputfile";
std::fstream file(p);

// Read file content
std::string str;
std::getline(file, str);

// Truncate file
fs::resize_file::resize_file(p, 0);

在此之前,使用 fstream 在标准 C++ 中是不可能的。您需要使用系统特定的代码,如 SetEndOfFile()在 Windows 或 ftruncate()在 Linux 上

另见

关于c++ - 如何在文件仍处于打开状态时删除文本文件的内容(无需重新打开文件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59158179/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com