C++ 将字符串写入文件开头
C++ Write string to beginning of file
我有一个文件,如下所示
这是第 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 行",然后复制现有文件的内容。
相关文章:
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 如何在 的开头<x>和结尾<y>之间更改带有文件输出的字符串的值
- 如何在C++中.txt文件的开头插入字符串
- 帧提取 使用OpenCV的视频文件开头只有几秒钟
- 我想删除 txt 文件中以 %% ( C++) 开头的一些行
- 如何转到 fstream 中文件的开头?
- ifstream 读取以 开头的每个文件
- C++从文件中读取不同类型的数据,直到有一个以数字开头的字符串
- 从文件的开头读取,而不会浪费太多内存
- 写入文件开头,保留文件内容
- 将头文件(.h)放在另一个文件(.h或.cpp)的开头和结尾之间的区别
- c++写入文件当前行的开头
- C++ 将字符串写入文件开头
- C++fread读取文件开头的随机字符
- 文件开头的垃圾字符
- c++从文件开头读取到指定字节
- 'BOM'字符在文件开头或文件末尾的位置是什么?
- 从文本文件开头的行中删除空格
- 如何在C++中的文件开头添加一行
- 有没有一种在文件开头添加一位的快速方法/技巧