fstream<<操作不写整个输出

时间:2016-04-24 08:50:40

标签: c++ stream fstream

直到f<<< “string”<< temp_int<< ENDL;声明    使用不同的openmodes得到不同的结果,要么根本不写,要么写出“NumberSaves”的前两个字符

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
}

期望的输出如下

  

NumberSaves 2
  玩家
  anotherplayer

当前输出

  


  播放器

1 个答案:

答案 0 :(得分:0)

像这样正确使用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。