0

私はDev-C++ IDEを使用していますが、今はファイル処理をしようとしています.hereは私のコードです:

int main(){
     FILE *fp;
     int b = 10;
     int f;
      fp = fopen("data.txt", "w");
      //checking if the file exist
      if(fp == NULL){
        printf("File does not exist,please check!\n");
      }else{
      printf("we are connected to the file!\n");
      }
      fprintf (fp, " %d ", b) ;
      fclose(fp);
      printf("Reading from the file \n");

      FILE *fr;
      fr=fopen("data.txt","r");
      fscanf (fr, " %d ", &f) ;
      fclose(fr);
      printf("the data from the file %d \n", f);
    return 0;

}

このコードは NetBeans では機能しますが、Dev-C++ では「ファイルに接続されています」というメッセージが表示されますが、値「10」がファイルに入力されません。答えを教えてください、どうすればいいですか?

4

2 に答える 2

2

コードに問題はありませんが、ここにいくつかのヒントがあります

すべてをインラインにするのではなく、関数を作成して呼び出すのが良い習慣です。

#define FILENAME "data.txt"

void writeFile()
{
     FILE *fp;
     int b = 10;
      fp = fopen(FILENAME, "w");
      //checking if the file exist
      if (fp == NULL)
      {
        perror("File could not be opened for writing\n");
      }
      else
      {
        printf("File created\n");
      }
      fprintf (fp, " %d ", b) ;
      fclose(fp);
}

void readFile()
{
     int f;
     printf("Reading from the file \n");

     FILE *fr;
     fr=fopen(FILENAME,"r");
     fscanf (fr, " %d ", &f) ;
     fclose(fr);
     printf("the data from the file %d \n", f);
}

int main()
{
  writeFile();
  readFile();
}

次に、ファイルから読み取るときは、fscanfは値が予期しない場合にメモリを上書きする傾向があるため、より安全に使用できるため、代わりにfgetsを使用することをお勧めします。

<- fscanf(fp," %d ", &f );

-> char buf[16]; // some buffer
-> fgets( fp, buf, 10 ); // read as string
-> f = atoi(buf); // convert to int
于 2010-11-20T11:20:05.177 に答える