使用fstream读取和写入同一文件 [英] Reading and writing to the same file using fstream

查看:110
本文介绍了使用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?

推荐答案

在没有中间寻道的情况下在文件流的输入和输出之间切换时,会出现不确定的行为.无论您在哪里寻找都可以,但是您需要寻找!例如,您可以尝试将零个字符远离当前位置,或者更有可能返回到该值实际开始的位置:

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

但是请注意,流不会会为其他字符留出空间,即,如果读取的内容短于所写的内容,则将在originla输入之后覆盖数据.同样,您将只覆盖您覆盖的字符.我建议不要这样做.如果要更新文件,请确保您使用的是固定宽度的记录!

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!

当然,您也不应使用input.eof()来验证流是否良好:如果流进入故障模式(例如,由于输入格式错误),您将永远不会到达产生true,即,您将得到一个无限循环.只需使用流本身作为条件.就个人而言,我会使用类似的

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

这篇关于使用fstream读取和写入同一文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆