LibC: Use proper casting in fgetc and fgetc_unlocked functions

In the fgetc function, a fix was already in place but was clunky. A real
proper solution is to use an unsigned char instead of a char when
returning the value, so an implicit cast is happening based on the
assumption that the value is unsigned, so if the variable contained 0xff
it won't be treated as -1, but as unsigned 0xff, so the result int will
be 0xff and not -1.

The same solution is applied to the fgetc_unlocked function as well.
This commit is contained in:
Liav A 2022-10-17 20:34:21 +03:00 committed by Andreas Kling
parent 1a84cb5457
commit 74a080fb68
Notes: sideshowbarker 2024-07-17 06:24:08 +09:00

View file

@ -631,12 +631,10 @@ char* fgets(char* buffer, int size, FILE* stream)
int fgetc(FILE* stream)
{
VERIFY(stream);
char ch;
size_t nread = fread(&ch, sizeof(char), 1, stream);
unsigned char ch;
size_t nread = fread(&ch, sizeof(unsigned char), 1, stream);
if (nread == 1) {
// Note: We do this static_cast because otherwise when casting a char that contains
// 0xFF results in an int containing -1, so an explicit cast is required here.
return static_cast<int>(ch & 0xff);
return ch;
}
return EOF;
}
@ -644,8 +642,8 @@ int fgetc(FILE* stream)
int fgetc_unlocked(FILE* stream)
{
VERIFY(stream);
char ch;
size_t nread = fread_unlocked(&ch, sizeof(char), 1, stream);
unsigned char ch;
size_t nread = fread_unlocked(&ch, sizeof(unsigned char), 1, stream);
if (nread == 1)
return ch;
return EOF;