I'm using the basic expressions have been taught in the short videos but probably I'm implementing them wrong, especially I believe I'm using the wrong data types for my variables :/ My loop expression is:

FILE *inptr = fopen(argv[1], "r");
char ch; 
while ((ch = fgetc(inptr)) != EOF);

when I use my code like this it reads only first 512bytes then exits the loop. When I asssign

unsigned char ch;

terminal gives error:

result of comparison of constant -1 with expression of type 'unsigned char' is always true.

I think I'm wrong about my data type choice in here. Can someone explain me why I'm wrong and how should I approach this? TIA

EDIT: Also I've tried while loop with an if condition like this

while (1)
    fread(buffer, 512, 1, inptr);
    printf("%i times read\n", cnt);
    if (feof(inptr))

But this loop only works twice than exits the loop. I didn't implement any extra functions as I'm still at the beginning of this problem and firstly trying to work out the reading function


With regards to your first question, fgetc technically returns an int. While it expects to read a byte of data represented as an unsigned char, it will return a negative number (usually -1, and represented by the EOF constant) when at the end of file.

Assigning the result of fgetc to an unsigned char is fine (the result will be implicitly typecast) but you won't be able to test that variable for a negative result anymore. If fgetc returns -1, it will be wrapped and your unsigned char will have the value 255/0xFF.

I don't see any technical issues with your second loop, and running it myself works fine. Check your code outside the loop, and the file that's being read.

  • thanks a lot, now my code reads until the end of file and gets the correct amount of jpeg headers – cetins Oct 28 '20 at 10:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .