Reading and writing to the same file using fstream

﹥>﹥吖頭↗ 提交于 2019-12-13 02:36:43

问题


void Withdraw(int index, int amount)
{
    int Balindex = 0;
    fstream input("Balance.txt");
    float balance = 0.0;
    while ((!input.eof())&&(Balindex != index))
    {
        balance = 0.0;
        input >> balance;
        Balindex++;
    }
    input >> balance;
    balance = balance - amount;
    input << balance << endl;
}

i am trying to read balance from a text file, and deduct the amount withdrawn. index holds the chronological number of the balance. my file however wont overwrite the existing value with the new one. Any suggestions?


回答1:


When switching between input and output for a filestream without an intervening seek, you get undefined behavior. It doesn't matter where you seek to but you need to seek! For example, you can seek to zero characters away from the current position or, more likely, back to the position where the value actually started:

std::streampos start = input.seekg(0, std::ios_base::cur);
if (input >> balance) {
    input.seekp(start);
    input << (balance - amount);
}

Note, however, that the stream won't make space for additional characters, i.e., if what you read is shorter than what you write, you'll overwrite data following the originla input. Likewise, you will only overwrite the characters you overwrite. I'd recommened against doing anything like that. If you want to update a file, make sure you are using fixed width records!

Of course, you also shoudn't use input.eof() to verify if the stream is any good: if the stream goes into failure mode, e.g., due to a misformatted input, you'll never reach the point where input.eof() yields true, i.e., you'd get an infinite loop. Just use the stream itself as condition. Personally, I would use something like

while (input >> balance && Balindex != index) {
    ++Balindex;
}


来源:https://stackoverflow.com/questions/20545155/reading-and-writing-to-the-same-file-using-fstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!