开发者

freopen() in C causing an infinite loop!

I am usin开发者_StackOverflow中文版g freopen() function in C to read data from a file Data.txt and write the same data to an output file Output.txt .This is the code I am writing to do this.

#include<stdio.h>
#include<conio.h>

int main(void)
{
    int i,diff,number_of_inputs,num1,num2;
    freopen("Data.txt","r",stdin);
    freopen("Output.txt","w",stdout);
    scanf("%d",&number_of_inputs);
    for(i=0;i<number_of_inputs;i++)
    {
        scanf("%d %d",&num1,&num2);
        printf("%d %d",num1,num2);  
    }
    fclose(stdin);
    fclose(stdout);
    getch();
    return 0;
}

The Data.txt file contains:

3

10 12

10 14

100 200

But the output file contains a large volume of garbage numbers giving an impression of an infinite loop.Can someone tell me whats going wrong?


You need to run your code through a debugger. I think then it'll probably be blindingly obvious what the issue is.

Having said that, you do no error checking on any of your library calls. If any of them fail, you'll just have garbage values in your variables.


Your code needs to check the return values from freopen() and scanf().

An unexpected return value from either of those functions will give you clues as to what is going wrong.

freopen() returns NULL to indicate an error.

scanf() returns the number of items converted, or EOF.

In either case your code can examine the value of errno to find out what caused the error. You will probably want to print it using perror().


Aside from the lack of newlines, that seems to run fine on my machine - the output is 10 1210 14100 200, which when appropriately newlined, gives

10 12
10 14
100 200

.

Also, getch() is a strange choice, given that you've just called fclose() on stdin

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜