0

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))
        {
            putchar(c);
        }

        fclose(fp);
    }

    return 0;
}
philant
  • 34,748
  • 11
  • 69
  • 112
pstap92
  • 191
  • 1
  • 1
  • 4

1 Answers1

6

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);
}
cnicutar
  • 178,505
  • 25
  • 365
  • 392