File reading in C language

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

-------------Problems Reply------------

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.

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);
}

Category:c# Views:2 Time:2017-09-11
Tags: file

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.213 (s). 10 q(s)