私は当初、このプログラムを単純に 10 進整数のバイナリ形式を表示するために作成しましたが、単純prinf()
にビットを並べて出力するだけだったので、粗いことがわかりました。sprintf()
使用sscanf()
して表示します。
しかし、結果をファイルに書き込み、取得して画面に表示fprintf()/fscanf()/printf()
したい場合、コンボには計り知れない問題があります。単に破損した出力が表示されるだけです。奇妙なことに、メモ帳でファイルを開くと、そこには意図した整数のバイナリ形式があります.しかし、それは画面に表示されません.小さな問題のようですが、何がわかりません.あなたの答えに感謝します.fprintf()
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àþ#