1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 13:57:35 +00:00

LibC: Fix fread() EOF behavior with ungetc().

This commit is contained in:
Andreas Kling 2019-03-27 05:13:28 +01:00
parent e145344767
commit f1a2cb0882

View file

@ -146,6 +146,7 @@ int ungetc(int c, FILE* stream)
ASSERT(stream); ASSERT(stream);
stream->have_ungotten = true; stream->have_ungotten = true;
stream->ungotten = c; stream->ungotten = c;
stream->eof = false;
return c; return c;
} }
@ -209,20 +210,26 @@ size_t fread(void* ptr, size_t size, size_t nmemb, FILE* stream)
if (!size) if (!size)
return 0; return 0;
ssize_t nread = 0;
if (stream->have_ungotten) { if (stream->have_ungotten) {
// FIXME: Support ungotten character even if size != 1. // FIXME: Support ungotten character even if size != 1.
ASSERT(size == 1); ASSERT(size == 1);
((char*)ptr)[0] = stream->ungotten; ((char*)ptr)[0] = stream->ungotten;
stream->have_ungotten = false; stream->have_ungotten = false;
--nmemb; --nmemb;
if (!nmemb)
return 1;
ptr = &((char*)ptr)[1]; ptr = &((char*)ptr)[1];
++nread;
} }
ssize_t nread = read(stream->fd, ptr, nmemb * size); ssize_t rc = read(stream->fd, ptr, nmemb * size);
if (nread < 0) if (rc < 0)
return 0; return 0;
if (nread == 0) if (rc == 0)
stream->eof = true; stream->eof = true;
nread += rc;
return nread / size; return nread / size;
} }