[libc-commits] [libc] [libc][stdio] Implement getline and getdelim POSIX functions (PR #219601)

Victor Campos via libc-commits libc-commits at lists.llvm.org
Tue Sep 8 02:59:06 PDT 2026


================
@@ -0,0 +1,80 @@
+//===-- Implementation for getline and getdelim -------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--------------------------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC_STDIO_INLINE_GETLINE_H
+#define LLVM_LIBC_SRC_STDIO_INLINE_GETLINE_H
+
+#include "hdr/func/free.h"
+#include "hdr/func/malloc.h"
+#include "hdr/func/realloc.h"
+#include "hdr/types/FILE.h"
+#include "hdr/types/size_t.h"
+#include "hdr/types/ssize_t.h"
+#include "src/__support/File/file.h"
+#include "src/__support/libc_errno.h"
+#include "src/__support/macros/attributes.h"
+#include "src/__support/macros/config.h"
+
+constexpr int INIT_BASE = 32;
+
+namespace LIBC_NAMESPACE_DECL {
+
+LIBC_INLINE ssize_t __getline(char **__restrict lineptr, size_t *__restrict n,
+                               int del, ::FILE *__restrict stream) {
+  if (!lineptr || !n || !stream) {
+    libc_errno = EINVAL;
+    return -1;
+  }
+
+  auto *file = reinterpret_cast<LIBC_NAMESPACE::File *>(stream);
+
+  if (*lineptr == nullptr) {
+    *n = (*n == 0) ? INIT_BASE : *n;
+    *lineptr = static_cast<char *>(malloc(*n));
+    if (!*lineptr) {
+      libc_errno = ENOMEM;
+      return -1;
+    }
+  }
+  uint8_t c = 0;
+  size_t bytes_read = 0;
+  file->lock();
+  while (true) {
+    auto result = file->read_unlocked(&c, 1);
----------------
vhscampos wrote:

Reading one byte at a time is inefficient. However I believe the File class does not provide access to the buffer directly without going through a read operation.

This inefficient implementation may be enough for now, or a more efficient impl that warrants new File API may be required.

(`fgets` also has a naive impl FWIW).

Tagging @michaelrj-google anc @sivachandra as they have worked on the File implementation.

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


More information about the libc-commits mailing list