0

コード:

struct subscriber
{
char phonenumber[20];
char name[50];
float amount;
}s;

void addrecords()
{
  FILE *f;
  char test;
  f=fopen("file.txt","ab+");
  //if(f==0)
  //{   f=fopen("file.txt","wb+");
    //system("clear");
    //printf("please wait while we configure your computer");
    //printf("/npress any key to continue");
    //getchar();
    //getch();
  //}

  while(1)
  {
    //system("clear");
    printf("\n Enter phone number:");
    scanf("%s",s.phonenumber);
    printf("\n Enter name:");
    fflush(stdin);
    //scanf("%[^\n]",s.name);

    scanf("%s",s.name);
    printf("\n Enter amount:");
    scanf("%f",&s.amount);
    printf("check 1");
    fwrite(&s,sizeof(s),1,f);
    fflush(stdin);
    printf("check 2");
    //system("clear");
    printf("1 record successfully added");
    printf("\n Press esc key to exit, any other key to add other record:");
    test=getchar();
    //test=getche();
    if(test==27)
      break;
  }
  fclose(f);
}

ここで2つの問題に直面しています:

  1. ファイルが作成されていますが、ファイルに何も書き込まれていません。
  2. 量を入力すると、すべての print ステートメントが出力され、getchar で待機しない while ループの最初に移動します。
4

3 に答える 3

1

最後scanf()は入力の最後にある改行を読み取らないため、getchar()すぐに戻り、待機しません。これが最初の問題の原因でもあり、ファイルが書き込まれないのは、プログラムを終了する必要があるためです。終了し、ファイルはフラッシュされません。そのため、最後の入力の最後に改行文字を消費する必要がありますscanf()

scanf("%f%*[^\n]%*c",&s.amount);

またはfgets()、行全体を読み取るために使用scanf()し、その上で使用します。最後に、fflush()入力ストリームをクリアするために使用しないでください。未定義です。

7.19.5.2.2 stream が、最新の操作が入力されていない出力ストリームまたは更新ストリームを指している場合、fflush 関数により、そのストリームの未書き込みデータがホスト環境に配信され、ファイルに書き込まれます。それ以外の場合、動作は未定義です。

于 2012-11-04T06:52:13.420 に答える
0

fflushをお持ちの場合は必要ありませんfclose

しかし、あなたのケースではwhile(1)fclose外側にあるというfcloseことは、呼び出されないことを意味するため、ファイルの内容が関数によって更新されることはありませんfclose

fflushの直後など、ループ内で使用するfwriteと、バッファが実際のファイルにフラッシュされます。

于 2012-11-04T06:51:32.560 に答える
0

You have named your file file.txt, so I assume you intend the file to be a text file? But then you open it with the b flag, which indicates binary format, and you write to it using fwrite, which doesn't convert the data to text, but just dumps the internal format to the file.

If you look at the created file in some sort of binary editor, you will see that it contains the data.

于 2012-11-04T06:53:22.893 に答える