Search code examples
c++fstream

Reading and writing to the same file using fstream


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?


Solution

  • 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;
    }