[英]Why is fprintf()/fscanf()/printf() showing wrong output in my Dec-to-Binary program,while printf() & sscanf() work fine?
我最初编写该程序只是为了显示十进制整数的二进制形式,但是我发现它很粗糙,因为它只是使用prinf()
并排打印位。所以我使用sprintf()
将其写入字符串并当我使用sscanf()
检索并显示它时,它工作正常。
但是如果我想使用fprintf()
将结果写入文件,使用fscanf()
检索并在屏幕上显示它,则fprintf()/fscanf()/printf()
组合存在一些无法想象的fscanf()
。显示损坏的输出。奇怪的是,当我在记事本中打开文件时,它在那里具有预期的整数形式的二进制形式。但是它不会在屏幕上显示出来。似乎是一个小问题,但我不能弄清楚是什么。我将感谢您的回答。
编辑您可以直接跳到零件rewind(fp)
,因为问题可能出在其后的3行中。
#include<stdio.h>
#include<stdlib.h>
void bform(int);
int main()
{
int source;
printf("Enter the integer whose binary-form you want\n");
scanf("%d",&source);
printf("The binary-form of the number is :\n");
bform(source);
return 0;
}
void bform(int source)
{
int i,j,mask;
char output[33],foutput[33];
FILE *fp;
fp=fopen("D:\\final.txt","w");
if(fp==NULL)
{
printf("I/O Error");
exit(-1);
}
for(i=31; i>=0; i--)
{
mask=1;
//Loop to create mask
for(j=0; j<i; j++)
{
mask=mask*2;
}
if((source&mask)==mask)
{
sprintf(&output[31-i],"%c",'1');
printf("%c",'1');
fprintf(fp,"%s","1");
}
else
{
sprintf(&output[31-i],"%c",'0');
printf("%c",'0');
fprintf(fp,"%s","0");
}
}
printf("\nThe result through sprintf() is %s",output);
rewind(fp);
fscanf(fp,"%s",foutput);
printf("\nThe result through fprintf() is %s",foutput); //Wrong output.
fclose(fp);
}
输出:
Enter the integer whose binary-form you want 25
The binary-form of the number is :
00000000000000000000000000011001
The result through sprintf() is 00000000000000000000000000011001
The result through fprintf() is ÃwxÆwàþ#
因为您打开了文件以进行只写访问。 您无法从中读取数据,也没有检查fscanf
的返回值,因此看不到它失败了。
如果您还希望能够读回您编写的内容,请将模式"w"
更改为"w+"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.