opu 웃
opu 웃

Reputation: 462

File is taking input infinitely

I have following C program:

#include <stdio.h>

int main()
{
    FILE *f1, *f2, *f3;
    int number, i;

    printf("Contents of data file\n\n");

    f1=fopen("DATA", "w");

    for(i=1; i<=10; i++)
    {
        scanf("%d", &number);

        if(number==-1)
        {
            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");
    f2=fopen("EVEN","r");

    printf("Contents on ODD file:");
    while((number=getw(f2)) != EOF)
    {
        printf("%4d", number);
    } 

    printf("Contents on EVEN file:");
    while((number=getw(f3)) != EOF)
    {
        printf("%4d", number);
    }

    fclose(f2);
    fclose(f3);

    return 0;

}

This program is taking input infinitely for FILE f1. After pressing -1 it should be terminated. But its not! I have pressed CTRL+D. But nothing happened. I am not understanding where is the problem.

Upvotes: 0

Views: 103

Answers (3)

Heeryu
Heeryu

Reputation: 872

i guess you mean

(number=getw(f1))

instead of

(number==getw(f1))

Your program is going to loop forever on your first while clause in this way.

And you should be opening your files with "wb" and "rb" instead of "w" and "r", because putw() and getw() both expect files opened in binary mode.

Upvotes: 4

PoornaChandra
PoornaChandra

Reputation: 351

You have written

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

but it should be written

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

any way, heena has corrected this... the EVEN stream should be pointed by f3

Upvotes: 0

Heena Goyal
Heena Goyal

Reputation: 380

i have tried the same code with some small corrections and it is working fine try this if helpful:

int main()
{
 FILE *f1, *f2, *f3;
int number, i;

printf("Contents of data file\n\n");

f1=fopen("DATA", "w");

for(i=1; i<=10; i++)
{
    scanf("%d", &number);

    if(number==-1)
    {
        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("Contents on ODD file:");
while((number=getw(f2)) != EOF)
{
    printf("%4d", number);
} 

printf("Contents on EVEN file:");
while((number=getw(f3)) != EOF)
{
    printf("%4d", number);
}

fclose(f2);
fclose(f3);

return 0;

}

Upvotes: 0

Related Questions