从文件中读取值、更改值和更新文件

Reading value from a file, altering value and updating file

本文关键字:文件 更新 读取      更新时间:2023-10-16

我正在处理一个简单的工资申请。我有一个包含 4 个选项的菜单和一个名为"shop-account"的文本文件,该文件仅包含值 100。对于选项一,用户应该能够从这 100 中转移金额。用户应该能够进行多次交易,但不能透支帐户。

目前,我刚刚打开文件并将值 100 声明到 int "余额",然后要求用户输入要转移的金额("NewAmount")并简单地减去它。但是,这仅适用于一个事务。

当我返回并尝试进行第二次转账时,它会再次从 100 中减去,而不是更新的金额。所以我想知道是否有人知道我将如何在每次交易后更新文件?

int balance;
int NewAmount;

fstream infile;
infile.open("shop-account.txt");
infile >> balance;
do {
    cout << "1. Transfer an amount" <<endl;
    cout << "2. List recent transactions"<<endl;
    cout << "3. Display account details and current balance"<<endl;
    cout << "4. Quit" << endl;
    cout << "Please enter menu number"<<endl;
    cin >> selection;
    switch(selection) {
    case 1: 
        cout << "You have choosen to transfer an amount" << endl;
        cout << "How much do you wish to transfer from the shop account?"<<endl;
        cin >> NewAmount;
        cout << balance - NewAmount << endl;
        break;
    case 2:
        cout << "Here are you're recent transactions" <<endl;
        cout << "" << endl;
        cout << "" << endl;
        break;
    case 3:
        cout << "The account names is:" << name << endl;
        cout << "The account number is:" << number << endl;
        cout << "The current balance isnn" << endl; //Need to get cuurent balance still
        break;
    case 4:
        return 0;
        break;
    default:
        cout << "Ooops, invalid selection!" << endl;
        break;
    }
} while(selection != 4);
    system("pause");
return 0;
}

基本上你的文件只包含一个数据,所以做部分更新根本没有意义。

您所要做的就是像您一样在开头阅读它,并在每次进行交易时完全写回它。

int read_balance (void)
{
    fstream f;
    f.open("shop-account.txt");
    f >> balance;
    f.close();
    return balance;
}
void write_balance (int balance)
{
    fstream f;
    f.open("shop-account.txt");
    f << balance;
    f.close();
}

然后在您的代码中:

cout << "You have choosen to transfer an amount" << endl;
cout << "How much do you wish to transfer from the shop account?"<<endl;
cin >> NewAmount;
balance -= NewAmount;
write_balance (balance);
cout << balance << endl;

要"更新"文件,您必须使用正在"更新"的更改部分写入整个文件。

最有效的方法是对文件进行内存映射(在Unix中mmap()),在内存中更新它,并允许操作系统将更改后的版本刷新回磁盘(定期或在关闭时)。