gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:21:31 24 4
gpt4 key购买 nike

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

每当我使用 printf 运行该函数时,所有内容都会完美地打印到控制台。当我使用 fprintf 时,最后打印的 this 最终出现在文本文件的开头。

知道为什么会发生这种情况以及我可以采取什么措施来解决它吗?

我的打印功能的代码如下:

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

}
}

最佳答案

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

关于c - ansi C fprintf ("File_Name","a") 将最后打印的字符串放在文件顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42617447/

24 4 0