Luna/apps/mktemp.cpp

41 lines
1.0 KiB
C++
Raw Permalink Normal View History

2023-06-03 10:15:57 +00:00
#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());
2023-06-03 10:15:57 +00:00
return 0;
}