1

I am trying to read a file in C language

while(1){
        if(feof(file)){
            break;
        }
        printf("%c",fgetc(file));
    }

At the end I get special character like � I dont have anything like that in file

C Learner
  • 35
  • 3

2 Answers2

5

You can read a file step by step using the following code:

int ch;
while ((ch = fgetc(file)) != EOF) {
    putchar(ch);
}

This special character might be the EOF.

This question/answers might be interesting for you as well.

Community
  • 1
  • 1
pzaenger
  • 11,381
  • 3
  • 45
  • 46
0

From the man page for fgetc:

RETURN VALUE
       fgetc(),  getc()  and getchar() return the character read as an
       unsigned char cast to an int or EOF on end of file or error.

So you should check for feof before you use the return value of fgetc or you will print out the EOF character:

while(1){
        int c = fgetc(file);
        if(feof(file)){
            break;
        }
        printf("%c",c);
    }