如何在c ++中更新文件中的记录? [英] How can I update record in file in c++?

查看:57
本文介绍了如何在c ++中更新文件中的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面提到的功能代码中。我无法在文件my.dat中更新余额(存款和取款)。请告诉我哪里做错了。 (我是新手)。





In below mentioned code of function. I am not able to update balance(deposits and withdrawals) in file my.dat. Please advise where am I doing it wrong. (I am a newbie).


void dep_with(int e, int f)
{
    int amt;
    int recordFind=0;
    account ac;
    ifstream updatedata("E:\\c++ Project\\final thoughts\\my.dat", ios::in|ios::out);
    while(updatedata.read((char*) &ac, sizeof(ac)) && recordFind==0)
    {
        if(ac.get_account()==e)
        {
            ac.view_account();
            if(f==1)
            {
                cout<<"\nEnter the amount to be deposited";
                cin>>amt;
                ac.deposits(amt);
            }
            if(f==2)
            {
                cout<<"\nEnter the amount to be withdraw";
                cin>>amt;
                ac.withdrawls(amt);
            }
            int pos=(-1)*sizeof(ac);
            ofstream updatedata("E:\\c++ Project\\final thoughts\\my.dat", ios::in|ios::out|ios::app);
            updatedata.seekp(pos,ios::cur);
            updatedata.write((char*) &ac, sizeof(ac));
            cout<<"\n\n\tRecord Updated";
            recordFind=1;
        }

    }
    updatedata.close();
    if(recordFind==0)
    {
        cout<<"\n\nRecord not Found";
    }
}

推荐答案

首先,使用两个独立的流进行阅读并不是一个好主意写作。其次,将它们命名为相同( updatedata )是一个特别糟糕的主意。在进行搜索时,您指的是内部更新数据流的位置,该位置仍位于开头。因此你会写一个负面的位置,这可能会出错。



[已修改]

你为什么不使用fstream而不是ifstream。然后你可以使用相同的流进行读写。
For one, it's no good idea to work with two separate streams for reading and writing. And secondly, it is an especially bad idea to name them both the same (updatedata). When doing the seekp you are referring to the position of the inner updatedata stream, which is still positioned at the beginning. Hence you will be writing to a negative position, which will probably go wrong.

[AMENDED]
Why don't you use fstream instead of ifstream. Then you can do the reading and writing with the same stream.


这篇关于如何在c ++中更新文件中的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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