简体   繁体   中英

Why is fprintf()/fscanf()/printf() showing wrong output in my Dec-to-Binary program,while printf() & sscanf() work fine?

I initially wrote this program to simply display the binary-form of a decimal integer,but I found it crude since it simply used prinf() to print the bits side by side.So I used sprintf() to write it to a string and it works fine when I retrieve it using sscanf() and display it.

But there is some unfathomable problem with the fprintf()/fscanf()/printf() combo if I want to write the result to a file using fprintf() ,retrieve it using fscanf() and diplay it on the screen.It simply displays a corrupt output.The strange thing is when I open the file in notepad,it has the intended binary-form of the integer there.But it won't diplay that on the screen.Seems a minor problem,but I can't figure what.I'll appreciate your answer.

EDIT You can jump straight to the part rewind(fp) ,as the problem likely is in the 3 lines after it.

#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);

}

OUTPUT:

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àþ#

Because you opened the file for write-only access. You can't read from it, and you're not checking the return value of fscanf so you don't see that it failed.

Change the mode "w" to "w+" if you want to also be able to read back what you wrote.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM