From c2f8441572b3bec920522ca6ddff90c7ce23c6c3 Mon Sep 17 00:00:00 2001 From: Andrew Chambers Date: Mon, 30 Dec 2019 11:57:34 +1300 Subject: [PATCH] Add file/temp. --- src/core/io.c | 15 +++++++++++++++ test/suite7.janet | 6 ++++++ 2 files changed, 21 insertions(+) diff --git a/src/core/io.c b/src/core/io.c index b998e1a7..c84b85a9 100644 --- a/src/core/io.c +++ b/src/core/io.c @@ -136,6 +136,15 @@ static Janet cfun_io_popen(int32_t argc, Janet *argv) { } #endif +static Janet cfun_io_temp(int32_t argc, Janet *argv) { + (void)argv; + janet_fixarity(argc, 0); + FILE *tmp = tmpfile(); + if (!tmp) + janet_panicf("unable to create temporary file - %s", strerror(errno)); + return janet_makefile(tmp, JANET_FILE_WRITE|JANET_FILE_READ|JANET_FILE_BINARY); +} + static Janet cfun_io_fopen(int32_t argc, Janet *argv) { janet_arity(argc, 1, 2); const uint8_t *fname = janet_getstring(argv, 0); @@ -566,6 +575,12 @@ static const JanetReg io_cfuns[] = { "eprinf", cfun_io_eprinf, JDOC("(eprinf fmt & xs)\n\n" "Like eprintf but with no trailing newline.") + }, + { + "file/temp", cfun_io_temp, + JDOC("(file/temp)\n\n" + "Open an anonymous temporary file that is removed on close." + "Raises an error on failure.") }, { "file/open", cfun_io_fopen, diff --git a/test/suite7.janet b/test/suite7.janet index f7efb9a7..29e0561d 100644 --- a/test/suite7.janet +++ b/test/suite7.janet @@ -277,4 +277,10 @@ (assert (= (constantly) (constantly)) "comptime 1") +(with [f (file/temp)] + (file/write f "foo\n") + (file/flush f) + (file/seek f :set 0) + (assert (= (string (file/read f :all)) "foo\n") "temp files work")) + (end-suite)