diff --git a/runtime-light/k2-platform/k2-api.h b/runtime-light/k2-platform/k2-api.h index 524c5bd5c8..c519e32a0b 100644 --- a/runtime-light/k2-platform/k2-api.h +++ b/runtime-light/k2-platform/k2-api.h @@ -216,8 +216,8 @@ inline size_t pread(k2::descriptor descriptor, std::span buffer, uint return k2_pread(descriptor, buffer.size(), static_cast(buffer.data()), offset); } -inline size_t fgets(k2::descriptor descriptor, std::span buffer) noexcept { - return k2_fgets(descriptor, buffer.size(), static_cast(buffer.data())); +inline size_t readline(k2::descriptor descriptor, std::span buffer) noexcept { + return k2_readline(descriptor, buffer.size(), static_cast(buffer.data())); } inline void* mmap(k2::descriptor* md, void* addr, size_t length, int32_t prot, int32_t flags, k2::descriptor fd, uint64_t offset) noexcept { diff --git a/runtime-light/k2-platform/k2-header.h b/runtime-light/k2-platform/k2-header.h index 605dbd23c1..202dfbedc2 100644 --- a/runtime-light/k2-platform/k2-header.h +++ b/runtime-light/k2-platform/k2-header.h @@ -357,11 +357,11 @@ size_t k2_read(uint64_t stream_d, size_t buf_len, void* buf); size_t k2_pread(uint64_t stream_d, size_t buf_len, void* buf, uint64_t offset); /** - * equivalent to libc's `fgets` function + * behavior is similar to libc's `fgets` function, except that EOF and empty string return the same result. * * @return `0` if EOF is reached or an error occurs. total number of bytes read otherwise */ -size_t k2_fgets(uint64_t stream_d, size_t buf_len, void* buf); +size_t k2_readline(uint64_t stream_d, size_t buf_len, void* buf); /** * Semantically equivalent to libc's `mmap` function. diff --git a/runtime-light/stdlib/file/file-system-functions.cpp b/runtime-light/stdlib/file/file-system-functions.cpp index b360327cec..905dbda5c3 100644 --- a/runtime-light/stdlib/file/file-system-functions.cpp +++ b/runtime-light/stdlib/file/file-system-functions.cpp @@ -396,6 +396,10 @@ Optional f$fgets(const resource& stream, int64_t length) noexcept { return false; } + if (length == 1) { + return string{}; + } + auto file_resource{from_mixed>(stream, {})}; if (file_resource.is_null()) { return false; @@ -418,7 +422,7 @@ Optional f$fgets(const resource& stream, int64_t length) noexcept { return false; } string res{static_cast(length), false}; - auto read_res{k2::fgets(file.descriptor(), std::as_writable_bytes(std::span{res.buffer(), res.size()}))}; + auto read_res{k2::readline(file.descriptor(), std::as_writable_bytes(std::span{res.buffer(), res.size()}))}; if (read_res == 0) { return false; diff --git a/tests/phpt/dl/473_fgets.php b/tests/phpt/dl/473_fgets.php index 56db23e791..03d1d6b54e 100644 --- a/tests/phpt/dl/473_fgets.php +++ b/tests/phpt/dl/473_fgets.php @@ -1,5 +1,6 @@ @ok