从文件中读取值、更改值和更新文件
Reading value from a file, altering value and updating file
我正在处理一个简单的工资申请。我有一个包含 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()
),在内存中更新它,并允许操作系统将更改后的版本刷新回磁盘(定期或在关闭时)。
相关文章:
- 已修改的LinkedList未在文本文件本身中更新
- 如何更新和删除文本文件中的特定逗号分隔值?C++
- C++中的文件处理:更新行
- 更新到 2020 年 5 月版本后,无法在 Visual Studio 2019 中创建.exe文件
- 尝试使用 EvtSetChannelConfigProperty() 函数更新最大事件日志文件大小时插入的错误值
- Chilkat SFTP 文件修改时间不与上传更新
- 如何在文件中更新
- 你能把文件嵌入到exe中,每次使用都更新吗
- 更新文件请求将导致404
- 如果您有Visual Studio 2017 Preview 2更新,您可以为我提供include/iosfwd文件吗?
- 在生成文件中添加源文件并更新依赖项
- 如何确保我的"ifstream"文件对象指向的文件内容已更新?
- 如何使用C++删除/更新txt文件中的特定数据
- 如何使用C++删除/更新txt文件中的特定数据?
- 如何更新/订购'Android.mk'文件?
- 从二进制文件C++更新数据
- Condor输出文件更新
- 使用boost:asio和select?阻止TCP输入或文件更新
- 连续文件更新,递归函数
- 当.h文件更新时,是否应该更新库