开发者

Why these c code not working? Whats wrong with these?

#include < stdio.h >

#include < string.h >

int main()

{

unsigned char a;

FILE *P;

P=fopen("mola.txt","r");

while((a=getc(P))!=EOF)

printf("%c",a);

}

Whats wrong with these code? When I compile it gives warning "comparison is always true due 开发者_运维知识库to limited range of data type." What does that warning mean?


You are storing the result of getc in a char. It should be an int. There's also a C FAQ on it. Also you should check the return value of the fopen.

P=fopen("mola.txt","r");
if (NULL == P) {
    perror("fopen"):
}

Also the while looks fishy. Try indenting ?

while((a=getc(P)) != EOF)
    printf("%c",a);


It means just what it says

comparison is always true due to limited range of data type.

The range of the data type in question (the a, which is unsigned char) is from 0 to 255 (really UCHAR_MAX);

The EOF value is -1

You are comparing a (from 0 to 255) with -1

(a != -1)

the condition will always be true


Try:

#include <stdio.h>
#include <string.h>
int main()
{
int a;
FILE *P;
P=fopen("tryit2.c","r");
while(EOF != (a = fgetc(P))) {
        printf("%c",a);
    }
}

You had two problems "getc()" returns an integer not a character. And the while statement had some weird side effects in the original order.


It means the loop will fell into Infinite loop not allowing the program to exit when at a=getc(p).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜