[libc-commits] [libc] [libc] Add getc, ungetc, fflush to enable libc++ iostream on baremetal (PR #175530)

Volodymyr Turanskyy via libc-commits libc-commits at lists.llvm.org
Tue Jan 13 08:53:29 PST 2026


================
@@ -32,11 +32,28 @@ struct FileIOResult {
   constexpr operator size_t() { return value; }
 };
 
+// ungetc handling.
+int store_ungetc_value(::FILE *stream, int c);
+bool pop_ungetc_value(::FILE *stream, unsigned char &out);
+
 LIBC_INLINE FileIOResult read_internal(char *buf, size_t size, ::FILE *stream) {
-  ssize_t ret = __llvm_libc_stdio_read(stream, buf, size);
+  size_t ungetc_value_copied = 0;
+  if (size > 0) {
+    unsigned char ungetc_value = 0;
+    if (pop_ungetc_value(stream, ungetc_value)) {
+      buf[0] = static_cast<char>(ungetc_value);
+      ungetc_value_copied = 1;
+    }
+  }
+
+  if (ungetc_value_copied == size)
+    return ungetc_value_copied;
+
+  ssize_t ret = __llvm_libc_stdio_read(stream, buf + ungetc_value_copied,
+                                       size - ungetc_value_copied);
   if (ret < 0)
-    return {0, static_cast<int>(-ret)};
-  return ret;
+    return {ungetc_value_copied, static_cast<int>(-ret)};
----------------
voltur01 wrote:

One return is early one for the error case reported by `__llvm_libc_stdio_read` then the last one is the normal success case.

https://github.com/llvm/llvm-project/pull/175530


More information about the libc-commits mailing list