2016-04-24 62 views
-1

everthing进行得很顺利,直到f < <“string”< < temp_int < < endl;声明 得到不同openmodes不同的结果,无论是在所有不写或写“NumberSaves”fstream <<操作不写入整个输出

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

什么是'readVarFromFile()'?请提供[MCVE]。 –

+0

认识到寻找文件中的位置最适合以二进制模式打开的文件。如果文件以文本模式打开,则由于执行了新行和eof翻译,您将无法使用“seekp”,“tellp”等获得所需的结果。 – PaulMcKenzie

+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 ::到底是方向不是绝对的位置。这只是一个枚举值。该值可能是2,这就是为什么它将您带到文件中的位置2。

+0

但是说如果有5个已保存的玩家(全部在单独的行中),我无法在“保存次数”之后直接继续写入,因为它将覆盖玩家 –