[libc-commits] [libc] [libc] implement mkstemp (PR #199220)
Michael Jones via libc-commits
libc-commits at lists.llvm.org
Tue May 26 13:59:06 PDT 2026
================
@@ -0,0 +1,70 @@
+//===-- Implementation of mkstemp -----------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "src/stdlib/mkstemp.h"
+#include "hdr/errno_macros.h"
+#include "hdr/fcntl_macros.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/getrandom.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/open.h"
+#include "src/__support/common.h"
+#include "src/__support/libc_errno.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/null_check.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+LLVM_LIBC_FUNCTION(int, mkstemp, (char *tmpl)) {
+ LIBC_CRASH_ON_NULLPTR(tmpl);
+
+ cpp::string_view str_view(tmpl);
+ size_t count = 0;
+ size_t len = str_view.size();
+
+ for (size_t i = len; i > 0; i--) {
+ if (str_view[i - 1] != 'X')
+ break;
+ count++;
+ }
+
+ if (count < 6) {
+ libc_errno = EINVAL;
+ return -1;
+ }
+
+ char *suffix = tmpl + len - count;
+
+ const char charset[] = "QWERTYUIOPASDFGHJKLZXCVBNM"
+ "qwertyuiopasdfghjklzxcvbnm"
+ "1234567890"
+ "._-";
+
+ while (true) {
----------------
michaelrj-google wrote:
The actual loop condition is that the file has not yet been created. Instead of using `while(true)` I'd recommend creating a `bool file_created` variable which starts as `false`. Then when the file is detected as successfully created it can be set to `true`. That way you can move the `return fd.value()` outside the loop, which will make control flow easier to understand.
https://github.com/llvm/llvm-project/pull/199220
More information about the libc-commits
mailing list