noufal
noufal

Reputation: 970

Output is not displying correctly in file operation

Can anybody explain what is the mistake in this code.

#include<stdio.h>
int main() {
  FILE *f1;
  char c;
  f1 = fopen("INPUT", "w");
  while((c=getchar()) != '/')
    putc(c, f1);
  fclose(f1);
  f1 = fopen ("INPUT", "r");
  while ((c = getc(f1) != EOF))
    printf("%c", c); 
  fclose(f1);
}

The output is coming in undetectable font. I tried in windows also. But the same result.

Upvotes: 0

Views: 73

Answers (1)

Nikos C.
Nikos C.

Reputation: 51870

First, c should be an int, not a char. putc() takes an int and, more importantly, getc() reads the next character from the stream and returns it as an unsigned char cast to an int, or EOF on end of file or error. If you store it into a char instead, EOF gets lost since char is too narrow and can't represent that. getc()

Second, this is wrong:

while ((c = getc(f1) != EOF))

what you want here is:

while ((c = getc(f1)) != EOF)

You've misplaced a parenthesis.

Remember that you need to alter your printf() call since c is now an int:

printf("%c", (char)c);

You need the explicit cast because printf() is a variadic function and therefore the compiler performs no automatic type conversion. You need to cast manually with variadic functions.

Upvotes: 2

Related Questions