Question

char ch;
while((ch = getchar()) != EOF){
    putchar(ch);
}

The above code, obviously enough, should copy my input. And it does work, for basic ASCII text files.

However, if I send it a gif, in particular this one, but applicable to most (http://www.cs.utexas.edu/~peterson/prog2/smile.gif), then when I redirect stdin for the gif, and stdout to any file type, and run diff on the original and the new one, errors galore. In this case, more than half of the file isn't even processed, it simply quits. Any clues? I'd be willing to switch off to another input/output functions, provided I can input a byte at a time.

Was it helpful?

Solution

getchar returns an int, not a char. The distinction is important because it might return EOF which is a value which cannot be a char.

You can't reliably test for EOF if you convert the return value of getchar to a char. The loop will terminate when you hit the character whose value is (char)EOF.

Fix it by declaring ch as an int.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top