2017-03-06 4 views
-2

コードを記述して関数を実行し、結果をファイルに出力する別の関数を呼び出すように指示されました。 print関数は複数回呼び出されるため、 "a"演算子を使用しました。ansi C fprintf( "File_Name"、 "a")は、最後に出力された文字列をファイルの先頭に置きます。

printfを使用して関数を実行すると、すべてがすべてコンソールに完全に出力されます。 fprintfを使用すると、最後に印刷されるのはテキストファイルの先頭になります。

これがなぜ起こっているのか、それを修正するために何ができるのでしょうか?私の印刷機能のための

コードは以下の通りです:

void WriteNos(int Case, int dec, long float Float) { 
    Output = fopen("cp2.out", "a"); /*initialize output file ins append mode so that file is not over written at every call function*/ 
    int j; /* initialize j counter for printing Float to dec*/ 
    switch (Case) 
    { 
    case 1:/* called from ConvertDecInt2binary */ 
    {fprintf(Output,"The binary representation of decimal \t \t %d is %s\n", dec, DectoBinarray); } /*dec in this case is the decimal integer used for ConvertDecInt2binary. DectoBinarray is a global array*/ 
     return; 
    case 2: /*Called from ConverBinary2Dec*/ 
    {fprintf(Output,"The decimal representation of binary \t%s is\t%d\n", BinarrayPrint, dec); }/*dec in this case is a decimal integer calculated in ConvertBinary2Decimal, BinarrayPrint is a global array*/ 
     return; 

    case 3:/*Called from ConvertFloatInt2Binary*/ 
    { fprintf(Output, "The binary representation of decimal \t \t%.6lf is %c ", Float, FloattoBinary[0]); /*Float is the Flot point number used in converDecFloat2binarynFloatBinary is a global array whole 0 location is the sign bit*/ 
      for (j = 1; j <= 8; j++) 
      { 
       fprintf(Output,"%c", FloattoBinary[j]); /*print the exponant in binary form*/ 
      } 
      fprintf(Output, " "); 
      for (j = 31; j >= 9; j--)/*print the mantissa in binarry form*/ 
      { 
       fprintf(Output,"%c", FloattoBinary[j]); 
      } 
      fprintf(Output,"\n"); /*Print a new line */ 
       return; 
      } 
     case 4: 
     { 
      fprintf(Output,"\n"); 
      return; 
     } 

     } 
    } 
+0

機能がある場合は、最後にファイルを閉じる必要があります。 – chux

+0

あなたの完全なコードを私たちに教えてください。一番上に印刷される「最後の」行はどれですか?また、上記のコメントで示唆されているように、ファイルポインタ 'fclose(output);を閉じて問題が解決したかどうか確認してください。 – VHS

+0

@VHS完全なコードではありません。 [MCVE](/ help/mcve)です。 –

答えて

1

使用fclose関数から復帰する前に。 また、毎回fopenの戻り値を確認してください。 またはOutputがグローバル変数(ローカル宣言が見つかりません)だと思います。だから毎回開閉する必要はありません。

関連する問題