ansi C fprintf(“File_Name”,“a”)将最后打印的字符串放在文件的顶部

时间:2017-03-06 04:14:42

标签: c

我已被指示编写代码以执行函数,然后调用另一个函数将结果打印到文件中。我使用“a”运算符,因为多次调用print函数。

每当我使用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;
        }

        }
    }

1 个答案:

答案 0 :(得分:1)

在从函数返回之前使用fclose。 还要每次检查fopen的返回值。 或者我认为Output是一个全局变量(没有找到本地声明)。所以不需要每次都打开和关闭。