0

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

}

4

3 回答 3

1

You need a few steps here:

int triedCreating = 0;

OPEN:
FILE *filePtr = fopen("test.txt", "r+");

if (!filePtr)
{
    // try to create the file
    if (!triedCreating)
    {
        triedCreating = 1;
        fclose(fopen("test.txt", "w"));
        goto OPEN;
    }
    fprintf(stderr, "Error opening file %i. Message: %s", errno, strerror(errno));
    exit(EXIT_FAILURE);
}

// scan for the float
float value = 0.0f;
fscanf(filePtr, "%f", &value);

printf("current value: %f\nvalue to add: ", value);

// add the new value
float add = 0.0f;
scanf("%f", &add);

value += add;

// write the new value
fseek(filePtr, 0, SEEK_SET);

fprintf(filePtr, "%f", value);

fclose(filePtr);

You may wish to have different formatting for your printf()'s so that it looks nicer when read into a normal text editor.

于 2012-03-14T19:25:35.533 回答
1

You should use a File pointer to open & read the file, modify the contents according to your will and write back to file.

For example:

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
于 2012-03-14T19:25:46.893 回答
0

您可以借助 C i 中的基本 FILE I/O(输入/输出)函数以简单的方式读取和编辑文件,例如,如果文件存在并且不创建具有名称的文件,则写入文件然后写信给它。

可以在 http://www.tutorialspoint.com/cprogramming/c_file_io.htm找到基本教程

现在,如果您谈论的是其中包含大量内容的复杂 .txt 文件,然后您需要找到一个特定的单词并对其进行更改,我发现在 Linux 中这有点困难,而您可以调用脚本来读取文件,使用 SED 编辑它,(用于过滤和转换文本的流编辑器)。您可以在以下链接中找到它的教程 http://www.panix.com/~elflord/unix/sed.html

于 2013-05-07T14:56:50.243 回答