开发者

How Can I Get getc() to Return a Character Besides a Smiley Face?

开发者 https://www.devze.com 2023-04-12 21:40 出处:网络
I am trying to write a simple \'cat\' clone in C. I\'m running Windows 7 and using the MinGW compiler. However, whenever I run the program, it returns the text file but with each character replaced wi

I am trying to write a simple 'cat' clone in C. I'm running Windows 7 and using the MinGW compiler. However, whenever I run the program, it returns the text file but with each character replaced with a '☺' character. Thank you in advance.

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;
    FILE *fp;
    int c;

    for(i = 1; i < argc; i++)
    {
        fp = fopen(argv[i], "r");

        if(fp == NULL)
        {
            fprintf(stderr, "cat: can't open %s\n", argv[i]);
            continue;
        }

        while((c = getc(fp) != EOF))
        {
        开发者_JAVA技巧    putchar(c);
        }

        fclose(fp);
    }

    return 0;
}


Since relational equal test (!=) has greater precedence than assignment (=) you'll just store 1 in c at every iteration. Put otherwise, one of the brackets is in the wrong place.

while((c = getc(fp) != EOF))
                          ^
{
        putchar(c);
}

Right:

while((c = getc(fp)) != EOF)
{
        putchar(c);
}
0

精彩评论

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