patelnisheet
patelnisheet

Reputation: 134

why putw on shows correct output with getw, and fprintf and printf only shows correct output with scanf?

Can anyone explain me whats exactly going on here? I have a problem in file management.

Explanation of code: Here, it takes integers from user and then stored in DATA file. then it reads integers from DATA file and filter them by ODD and EVEN and store it respective file.

Here is my code.

#include<stdio.h>
int main()
{
    FILE *f1, *f2, *f3;
    int number;

    printf("Enter the content of data file\n");
    f1 = fopen("DATA","w");
    for(int i=1;i<=30;i++)
    {
        /*problem is here*/
        number=getw(stdin);
        //scanf("%d",&number);

        if(number==-1 || number==EOF) break;
        putw(number,f1);
    }
    fclose(f1);


    f1 = fopen("DATA","r");
    f2 = fopen("ODD","w");
    f3 = fopen("EVEN","w");

    while((number = getw(f1))!=EOF)
    {       
        if(number % 2 == 0)
            putw(number, f3);
        else
            putw(number,f2);
    }
    fclose(f1);
    fclose(f2);
    fclose(f3);

    f2 = fopen("ODD","r");
    f3 = fopen("EVEN","r");

    printf("\n\ncontents of ODD file\n");

    while((number=getw(f2))!=EOF)
        /* problem is here */
        putw(number,stdout);        
        //fprintf(stdout,"%d\n",number);
        //printf("%d",number);

    printf("\n\ncontents of EVEN file\n");
    while((number=getw(f3))!=EOF)
        /*problem is here */
        //putw(number,stdout);
        fprintf(stdout,"%d\n",number);
        //printf("%d",number);

    fclose(f2);
    fclose(f3);
    printf("\n");
    return 0;
}

Output:

Enter the content of data file
111
222
333
444
555


contents of ODD file
111
333
555


contents of EVEN file
171061810
171193396

So here, why putw shows correct output with getw, and fprintf and printf only shows correct output with scanf. However, data stored in all files are correct!!!

why is it so?

Upvotes: 1

Views: 126

Answers (1)

Hitokiri
Hitokiri

Reputation: 3699

why putw shows correct output with getw, and fprintf and printf only shows correct output with scanf

Because the getw() function reads the next word from the stream. The size of a word is the size of an int and may vary from machine to machine`

You can see in the comment: 171061810 is 0xA323232 (it's a hex number). When you use the ASCII code to convert from hex to character, you get:

Hex    Character
A  ==> \n
32 ==> 2
32 ==> 2
32 ==> 2
so
171061810 is "\n222".

It's similar to 444.

Upvotes: 1

Related Questions