C++ 将字符串写入文件开头

C++ Write string to beginning of file

本文关键字:文件 开头 字符串 C++      更新时间:2023-10-16

我有一个文件,如下所示

这是第 1 行

这是第 2 行

我有一个字符串This is line 0.如何将此字符串写入文件的开头,以便文件的内容现在:

这是第 0 行

这是第 1 行

这是第 2 行

我目前有

ifstream myfile("lunch.txt");
myfile.seekg(0,ios::beg);
myfile << "This is line 0";

但它没有按预期工作。

写入std::ifstream(用于输入)是行不通的。更改代码以使用 std::ofstream 编写输出:

   ofstream myfile("lunch.txt");
// ^^^^^^^^
   // myfile.seekg(0,ios::beg); <<< this code isn't necessary
   myfile << "This is line 0";

为了解决您在现有内容之前插入的问题,您首先读取文件,同时将内容保存在例如std::vector<std::string> lines;中。然后再次打开文件,写第一行,然后用保存在lines中的值跟进。

不能插入到文件的开头并让现有内容自动移动。

最好的办法是打开一个新文件并写下"这是第 0 行",然后复制现有文件的内容。