【问题标题】:fstream << operate not writing entire outputfstream << 操作不写入整个输出
【发布时间】:2016-04-24 08:50:39
【问题描述】:

一切顺利,直到 f

unsigned int temp_int = 0;
 fstream f("resources/saveData/Player/savelog.txt");
 if (!f)
{
    cout << "error accessing savelist" << endl;
}
else
{
    string skip;
    std::stringstream iss;
    string line;
    readVarFromFile(f, iss, skip, line, { &temp_int });      //check how many saves currently
    temp_int += 1;                                           //increment number of saves by 1
    f.seekp(ios_base::beg);
    cout << "Write position: " << f.tellp() << endl;         //check stream is at beginning
    f << "<NumberSaves>" << temp_int << endl;                //truncate <NumberSaves> 'x' with <NumberSaves> 'x + 1'
    cout << "Write position: " << f.tellp() << endl;         //position suggests the entire string has been written, only two characters have been
    if (!f)
    {
        cout << "ERROR";
    }

    f.seekp(ios_base::end); 
    f << currentPlayer->getName();                           //append players name to end of file
}

想要的输出如下

数字保存 2
播放器
另一个玩家

电流输出


播放器

【问题讨论】:

  • 什么是readVarFromFile()?请提供minimal reproducible example
  • 意识到寻找文件中的某个位置最适合以二进制模式打开的文件。如果文件以文本模式打开,使用seekptellp 等将无法获得所需的结果,因为正在进行换行和eof 转换。
  • 这是我做的一个功能,不是问题的一部分,如果造成混乱,对不起

标签: c++ stream fstream


【解决方案1】:

像这样正确使用 seekp:

os.seekp(0, std::ios_base::end); // means bring me to 0 from the end of file.

查看示例代码 http://en.cppreference.com/w/cpp/io/basic_ostream/seekp

std::ios_base::end 是一个方向而不是绝对位置。它只是一个枚举值。该值可能是 2,这就是为什么它会将您带到文件中的位置 2。

【讨论】:

  • 但是说如果有 5 个保存的玩家(都在单独的行上),我不能在“保存次数”之后直接继续写入,因为它会覆盖一个玩家
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-23
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
  • 2020-08-13
  • 1970-01-01
相关资源
最近更新 更多