open/seekp/write正在截断文件
open/seekp/write is truncating file
描述:我有一个文本文件,其中有几行,我想在两行之间写入。
我尝试了什么:我有一个循环,它决定了我想写的位置。当我试图打开文件时,使用seekp定位输入,然后写入文件。文件被截断。
示例
file.txt:
Hello
Write under this line
Write above this line
代码:
ofstream myfileo;
myfileo.open("file.txt");
cout<<myfileo.tellp()<<endl;//starts at 0
myfileo.seekp(26);//move to 26 ...End of second line
cout<<myfileo.tellp()<<endl;//says 26
string institution ="hello";
myfileo<<"n"<<institution<<"n";
myfileo.close();
问题:我不确定文件被截断的原因。我试着使用append,但不管它到底写了什么,但我不确定自己做错了什么。
谢谢,JT
尝试做我在评论中发布的内容是可能的,但令人沮丧。以下是适用于这个特定示例的代码,但并非适用于所有情况:
#include <algorithm>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
int main (void)
{
std::fstream file ;
file.open ("test.txt") ;
file.seekg (28, file.beg) ; // 28 was the correct offset on my system.
auto begin = std::istream_iterator <std::string> (file) ;
auto end = std::istream_iterator <std::string> () ;
std::vector <std::string> buffer (begin, end) ;
file.clear () ; // fail-bit is sometimes set for some reaon.
file.seekg (28, file.beg) ;
file << "n" "hello" "n" ;
std::copy (std::begin (buffer), std::end (buffer),
std::ostream_iterator <std::string> (file, " ")) ;
return 0 ;
}
如果您不想将所有内容都加载到内存中,那么更好的解决方案是使用临时文件。让我们称之为temp.txt。然后你会:
- 将file.txt中的所有内容复制到temp.txt中,然后再插入文本
- 将要插入的文本插入temp.txt
- 将文件.txt的其余部分复制到temp.txt中
- 删除文件.txt
- 将temp.txt重命名为file.txt
步骤4和5是特定于操作系统的(除非您有一些可移植库可以做到这一点)。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 打开文件的正确模式是什么,以便 seekp() 的工作方式与在默认模式下打开的文件相同
- 使用 tellg() 和 seekp() 覆盖文件
- 如何在c++中使用seekg和seekp附加到文件,而不使用ios:app标志
- C ++ fstream 写入不适用于没有 seekg 和 seekp 的二进制文件
- 在处理二进制文件时了解 Seekg() 和 seekp()
- seekp() 位置在文件中新行的开头
- 使用 fstream 创建文件,如果它不存在使用 seekp/seekg?
- 登录到文件后使用tell和seekp设置块大小是否合理?
- open/seekp/write正在截断文件
- 同一文件上的 seekp()、seekg()、read() 和 write() 有问题