I try to extract a char by using unsigned char ch1 = fgetc(filePointer);
, but the value that's returned is allways 255
. Here's my code:
#include <stdio.h>
#include "anotherCFile.c"
int main(int argc, char **argv)
{
int ch;
FILE* filePointer;
filePointer = fopen("text.txt", "w+");
ch = fgetc(stdin);
while (ch!=EOF) {
fputc(ch, filePointer);
ch = fgetc(stdin);
}
unsigned char ch1 = fgetc(filePointer);
fclose(filePointer);
printf("%c", ch1);
return 0;
}
For any input I've checked (s.a. ABC
) the output is �
. When I change the line printf("%c", ch1);
to printf("%d", ch1);
the output is always 255
. I want to get the chars I've entered in the input.
(The text.txt
file is created properly). Thanks.
At the time of unsigned char ch1 = fgetc(filePointer);
filepointer
points to EOF(-1)
and in next statement you are printing ASCII
value of that which is 255(bcz ch is declared as unsigned)
.
EOF
defined as #define EOF (-1)
printf("%c\n,ch1); /* EOF is not printable char so it prints � */
printf("%d\n",ch1); /* fgetc() returns int, As char read is stored in a
variable of type int and that is EOF,and -1
equivalent unsigned value is 255 */
I want to get the chars I've entered in the input. ? do rewind() or fseek()
before reading.
rewind(filepointer);/* this is required to get first char of file */
unsigned char ch1 = fgetc(filePointer);
fclose(filePointer);
printf("%c", ch1);