ArkScript
A small, fast, functional and scripting language for video games
Files.hpp
Go to the documentation of this file.
1/**
2 * @file Files.hpp
3 * @author Alexandre Plateau ([email protected])
4 * @brief Lots of utilities about the filesystem
5 * @version 0.2
6 * @date 2021-11-25
7 *
8 * @copyright Copyright (c) 2021-2024
9 *
10 */
11
12#ifndef INCLUDE_ARK_FILES_HPP
13#define INCLUDE_ARK_FILES_HPP
14
15#include <string>
16#include <vector>
17#include <fstream>
18#include <filesystem>
19
20namespace Ark::Utils
21{
22 /**
23 * @brief Checks if a file exists
24 *
25 * @param name the file name
26 * @return true on success
27 * @return false on failure
28 */
29 inline bool fileExists(const std::string& name) noexcept
30 {
31 try
32 {
33 return std::filesystem::exists(std::filesystem::path(name));
34 }
35 catch (const std::filesystem::filesystem_error&)
36 {
37 // if we met an error than we most likely fed an invalid path
38 return false;
39 }
40 }
41
42 /**
43 * @brief Helper to read a file
44 *
45 * @param name the file name
46 * @return std::string
47 */
48 inline std::string readFile(const std::string& name)
49 {
50 std::ifstream f(name);
51 // admitting the file exists
52 return {
53 (std::istreambuf_iterator<char>(f)),
54 std::istreambuf_iterator<char>()
55 };
56 }
57
58 inline std::vector<uint8_t> readFileAsBytes(const std::string& name)
59 {
60 // admitting the file exists
61 std::ifstream ifs(name, std::ios::binary | std::ios::ate);
62 if (!ifs.good())
63 return std::vector<uint8_t> {};
64
65 const std::size_t pos = ifs.tellg();
66 // reserve appropriate number of bytes
67 std::vector<char> temp(pos);
68 ifs.seekg(0, std::ios::beg);
69 ifs.read(&temp[0], pos);
70 ifs.close();
71
72 auto bytecode = std::vector<uint8_t>(pos);
73 // TODO would it be faster to memcpy?
74 for (std::size_t i = 0; i < pos; ++i)
75 bytecode[i] = static_cast<uint8_t>(temp[i]);
76 return bytecode;
77 }
78
79 /**
80 * @brief Get the canonical relative path from a path
81 *
82 * @param path
83 * @return std::string
84 */
85 inline std::string canonicalRelPath(const std::string& path)
86 {
87 return relative(std::filesystem::path(path)).generic_string();
88 }
89}
90
91#endif
std::string readFile(const std::string &name)
Helper to read a file.
Definition: Files.hpp:48
bool fileExists(const std::string &name) noexcept
Checks if a file exists.
Definition: Files.hpp:29
std::string canonicalRelPath(const std::string &path)
Get the canonical relative path from a path.
Definition: Files.hpp:85
std::vector< uint8_t > readFileAsBytes(const std::string &name)
Definition: Files.hpp:58