Improve tmpfile api (#114)

This commit is contained in:
Justine Tunney 2021-03-07 21:07:16 -08:00
parent 2bd1e72d5a
commit 816b0e1851
3 changed files with 56 additions and 8 deletions

View file

@ -16,10 +16,14 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/bits/safemacros.internal.h"
#include "libc/calls/calls.h"
#include "libc/fmt/fmt.h"
#include "libc/macros.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/stdio/temp.h"
#include "libc/str/str.h"
/**
* Creates a temporary file.
@ -28,7 +32,13 @@
*/
FILE *tmpfile(void) {
int fd;
char template[] = "/tmp/tmp.XXXXXX";
if ((fd = mkostemps(template, 0, 0)) == -1) return NULL;
return fdopen(fd, "w+");
char *tmp, *sep, tpl[PATH_MAX];
tmp = firstnonnull(getenv("TMPDIR"), kTmpPath);
sep = !isempty(tmp) && !endswith(tmp, "/") ? "/" : "";
if (snprintf(tpl, PATH_MAX, "%s%stmp.XXXXXX", tmp, sep) < PATH_MAX) {
if ((fd = mkostemps(tpl, 0, 0)) != -1) {
return fdopen(fd, "w+");
}
}
return NULL;
}