std :: ofstream,覆盖错误的文件行

std::ofstream, Overwriting wrong file line

本文关键字:文件 错误 覆盖 ofstream std      更新时间:2023-10-16

我有一个将数据输出到文本文件的函数:

void File_IO::save( const std::string& path_ ) const
{
    const std::string file_name = path_ + this->local_time() + ".txt";
    std::ofstream outfile( file_name );
    std::vector<std::string> vec = { "One", "Two", "Three", "Four" };

    outfile << 'n' << 'n' << "//--------------------------------- DATA:" << 'n' << 'n';
    long pos_beg = outfile.tellp();
    for( auto& i : vec )
    {
        outfile << i << 'n';
    }
    long pos_end = outfile.tellp();
    outfile << 'n' << "//---------------------------------------" << 'n' << 'n';

    //outfile.seekp( 0 );   
    //outfile << pos_beg << " " << pos_end << " " << pos_beg << " " << pos_end;
}

输出:

//--------------------------------- DATA:
One
Two
Three
Four
//---------------------------------------

当涉及数据的开始/结束位置覆盖第一行时,问题发生在功能的末尾...添加这两行:

outfile.seekp( 0 ); 
outfile << pos_beg << " " << pos_end << " " << pos_beg << " " << pos_end;

输出:

49 72 49 72---------------------------- DATA:
One
Two
Three
Four
//---------------------------------------

如您所见,在到达标头之前,文件中有两个空行,但是它覆盖了这些,并部分删除了标题行,这是文件中的第三行,而不是预期的第一个行。

另一个线索:

如果我只写一个var,它似乎可以工作,但仍删除文件开始时的一个空行:

outfile.seekp( 0 ); 
outfile << pos_beg ;

输出:

49
//--------------------------------- DATA:
One
Two
Three
Four
//---------------------------------------

有人可以解释这里发生的事情,以及如何根据需要编辑功能工作?

ps不允许我出于某种原因添加相关标签

在正确方向上igor轻推的背面,将以下代码行添加到函数中似乎有效:

outfile << "                                                     " << 'n';

修订的功能:

void File_IO::save( const std::string& path_ ) const
{
    const std::string file_name = path_ + this->local_time() + ".txt";
    std::ofstream outfile( file_name );
    std::vector<std::string> vec = { "One", "Two", "Three", "Four" };
    // Edit
    outfile << "                                                     " << 'n';   
    // Edit
    outfile << 'n' << 'n' << "//--------------------------------- DATA:" << 'n' << 'n';
    long pos_beg = outfile.tellp();
    for( auto& i : vec )
    {
        outfile << i << 'n';
    }
    long pos_end = outfile.tellp();
    outfile << 'n' << "//---------------------------------------" << 'n' << 'n';

    outfile.seekp( 0 );   
    outfile << pos_beg << " " << pos_end << " " << pos_beg << " " << pos_end;
}

输出:

104 127 104 127                                      

//--------------------------------- DATA:
One
Two
Three
Four
//---------------------------------------

如果有人可以提供更好的答案并说出为什么,我会接受我的那个似乎有点幼体。