c - 如何用 C 语言读取和编辑 .txt 文件?

标签 c file-io read-write

我正在为 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/

相关文章:

c - Open() 输出不创建文件

c - 求 3 个骰子之和等于整数 k 的概率时的分割错误

file - 如何在matlab中将数据保存在32位二进制文​​件中?

c - 打印 double ,最后不加零?

python - 将 CSV 文件转换为 TF 记录

java - 如何打开并读取文件并将特定内容写入新文件?

c++ - 如何使用 STL C++ 读取文件和保存连字符

c - Write() 到文件描述符在 read() 时消失

c - C 中函数参数的范围

c - 使用 epoll 时 timerfd 将无法读取