fstream << 操作不写入整个输出

fstream << operate not writing entire output

一切顺利,直到 f << "string" << temp_int << endl;陈述 使用不同的打开模式得到不同的结果,要么根本不写,要么写 "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
player
anotherplayer

当前输出

Nu
player

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