我正在为 ATM 编写程序。我的 .txt
文件是帐户余额金额(在本例中为 1500.00)。如何读取 .txt
文件、编辑帐户余额,然后将其保存到文件中?
例如,如果我要求用户输入存款金额 300.00,我希望能够将 300.00 添加到文件中现有的 1500.00,然后用总金额 1800.00 覆盖 1500.00 .
这就是我到目前为止所拥有的。
float deposit;
float var;
printf("Current account balance:");
if ( (file_account = fopen ("account.txt", "r")) == NULL)
{
printf ("Error finding account balance.\n");
return;
}
while ( (fscanf (file_account, "%c", &var)) != EOF)
{
printf ("%c", var);
}
printf ("\n");
fclose (file_account);
for (deposit=0; deposit>0; deposit++)
{
if (deposit > 0)
{
printf ("Enter amount to deposit:");
scanf ("%f", &deposit);
//file_account + deposit;
fprintf (file_account, "Your new account balance is: %f", deposit);
}
else
{
printf ("Amount must be 0 or more.");
}
fclose (file_account);
}
最佳答案
您应该使用文件指针来打开和读取文件,根据您的意愿修改内容并写回文件。
例如:
File *fp; // creates a pointer to a file
fp = fopen(filename,"r+"); //opens file with read-write permissions
if(fp!=NULL) {
fscanf(fp,"%d",&var); //read contents of file
}
fprintf(fp,"%d",var); //write contents to file
fclose(fp); //close the file after you are done
关于c - 如何用 C 语言读取和编辑 .txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9708578/