open/seekp/write正在截断文件

open/seekp/write is truncating file

本文关键字:文件 seekp write open      更新时间:2023-10-16

描述:我有一个文本文件,其中有几行,我想在两行之间写入。

我尝试了什么:我有一个循环,它决定了我想写的位置。当我试图打开文件时,使用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。然后你会:

  1. file.txt中的所有内容复制到temp.txt中,然后再插入文本
  2. 将要插入的文本插入temp.txt
  3. 文件.txt的其余部分复制到temp.txt
  4. 删除文件.txt
  5. temp.txt重命名为file.txt

步骤4和5是特定于操作系统的(除非您有一些可移植库可以做到这一点)。