[英]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.