0

私はATM用のプログラムを書いています。私の.txtファイルは口座残高です (この場合は 1500.00)。.txtファイルを読み込んで口座残高を編集し、ファイルに保存するにはどうすればよいですか?

たとえば、ユーザーに 300.00 のデポジットを入力するように依頼した場合、その 300.00 をファイル内の既存の 1500.00 に追加し、1500.00 を合計金額の 1800.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

ファイルポインタを使用してファイルを開いて読み取り、必要に応じて内容を変更し、ファイルに書き戻す必要があります。

例えば:

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 に答える
1

ここでいくつかの手順が必要です。

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);

printf()通常のテキスト エディタで読み込んだときに見栄えがよくなるように、 の書式を変更したい場合があります。

于 2012-03-14T19:25:35.533 に答える
0

C の基本的な FILE I/O (入出力) 関数を使用して、ファイルの読み取りと編集を簡単に行うことができます。そしてそれに書き込みます。

基本的なチュートリアルは http://www.tutorialspoint.com/cprogramming/c_file_io.htmにあります。

多くのコンテンツを含む複雑な .txt ファイルについて話している場合、特定の単語を見つけて変更する必要があります。ファイル、SED(テキストのフィルタリングと変換のためのストリームエディタ)を使用して編集します。以下のリンクでチュートリアルを見つけることができます http://www.panix.com/~elflord/unix/sed.html

于 2013-05-07T14:56:50.243 に答える