Luna/apps/mktemp.cpp
apio 7d69ac56e2
All checks were successful
Build and test / build (push) Successful in 1m41s
apps+libos+shell+wind: Correct a bunch of format strings
2024-03-29 14:42:38 +01:00

41 lines
1.0 KiB
C++

#include <errno.h>
#include <luna/String.h>
#include <os/ArgumentParser.h>
#include <os/File.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
Result<int> luna_main(int argc, char** argv)
{
srand((unsigned)time(NULL));
bool make_directory { false };
StringView template_sv;
os::ArgumentParser parser;
parser.add_description("Create a temporary file or directory safely and print its name.");
parser.add_system_program_info("mktemp"_sv);
parser.add_switch_argument(make_directory, 'd', "directory"_sv, "make a directory instead of a file"_sv);
parser.add_positional_argument(template_sv, "template"_sv, "/tmp/tmp.XXXXXX"_sv);
parser.parse(argc, argv);
String str = TRY(String::from_string_view(template_sv));
if (make_directory)
{
if (mkdtemp(str.mutable_data()) == nullptr) return err(errno);
}
else
{
int fd = -1;
fd = mkstemp(str.mutable_data());
if (fd < 0) return err(errno);
close(fd);
}
os::println("%s", str.chars());
return 0;
}