-1

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.

J. Doe
  • 95
  • 8

2 Answers2

1

When you write to a *FILE ptr, its pointer is advanced and set to the end of file, ready to append the next char. To read some data back without reopening the file and reusing the same file pointer, you may want to rewind the pointer first.

Try to add

fseek(filePointer, 0, SEEK_SET);

before reading the data back

Francesco Laurita
  • 23,434
  • 8
  • 55
  • 63
1

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);
Achal
  • 11,821
  • 2
  • 15
  • 37