summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--cabinet/magic.cpp7
-rw-r--r--cabinet/magic.hpp3
-rw-r--r--cabinet/main.cpp18
3 files changed, 26 insertions, 2 deletions
diff --git a/cabinet/magic.cpp b/cabinet/magic.cpp
index 96b78a3..3c36881 100644
--- a/cabinet/magic.cpp
+++ b/cabinet/magic.cpp
@@ -3,8 +3,10 @@
#include <magic.h>
#include <cerrno>
+#include <cstddef>
#include <expected>
#include <filesystem>
+#include <span>
#include <string>
#include <string_view>
#include <system_error>
@@ -68,6 +70,11 @@ namespace cab
return handle_result(::magic_descriptor(m_cookie, file_descriptor));
}
+ auto magic::process(std::span<std::byte> data) -> std::expected<std::string, std::error_code>
+ {
+ return handle_result(::magic_buffer(m_cookie, data.data(), data.size_bytes()));
+ }
+
auto magic::handle_result(char const * result) -> std::expected<std::string, std::error_code>
{
auto errno_copy = errno;
diff --git a/cabinet/magic.hpp b/cabinet/magic.hpp
index 9e078de..68177f9 100644
--- a/cabinet/magic.hpp
+++ b/cabinet/magic.hpp
@@ -3,8 +3,10 @@
#include <magic.h>
+#include <cstddef>
#include <expected>
#include <filesystem>
+#include <span>
#include <string>
#include <string_view>
#include <system_error>
@@ -56,6 +58,7 @@ namespace cab
auto process(std::filesystem::path path) -> std::expected<std::string, std::error_code>;
auto process(int file_descriptor) -> std::expected<std::string, std::error_code>;
+ auto process(std::span<std::byte> data) -> std::expected<std::string, std::error_code>;
private:
auto handle_result(char const * result) -> std::expected<std::string, std::error_code>;
diff --git a/cabinet/main.cpp b/cabinet/main.cpp
index ff35d34..3602142 100644
--- a/cabinet/main.cpp
+++ b/cabinet/main.cpp
@@ -1,8 +1,13 @@
#include <cabinet/magic.hpp>
#include <fcntl.h>
+#include <unistd.h>
+#include <array>
+#include <cerrno>
+#include <cstddef>
#include <cstdlib>
+#include <cstring>
#include <iostream>
#include <print>
@@ -23,12 +28,21 @@ auto main(int argc, char ** argv) -> int
return EXIT_FAILURE;
}
- auto fd = open(argv[1], O_RDONLY);
- auto mime_type = magic->process(fd);
+ auto fd = ::open(argv[1], O_RDONLY);
+ if (fd < 0)
+ {
+ std::println(std::cerr, "Failed to determine file type: {}", ::strerror(errno));
+ return EXIT_FAILURE;
+ }
+
+ std::array<std::byte, 512> buffer{};
+ ::read(fd, buffer.data(), buffer.size());
+ auto mime_type = magic->process(buffer);
if (!mime_type)
{
std::println(std::cerr, "Failed to determine file type: {}", mime_type.error().message());
return EXIT_FAILURE;
}
+
std::println("{}: {}", argv[1], mime_type.value());
}