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.3
6 * @date 2024-07-09
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 /**
59 * @brief Helper to read the bytes of a file
60 * @param name filename
61 * @return std::vector<uint8_t>
62 */
63 inline std::vector<uint8_t> readFileAsBytes(const std::string& name)
64 {
65 // admitting the file exists
66 std::ifstream ifs(name, std::ios::binary | std::ios::ate);
67 if (!ifs.good())
68 return std::vector<uint8_t> {};
69
70 const auto pos = ifs.tellg();
71 if (pos == 0)
72 return {};
73 // reserve appropriate number of bytes
74 std::vector<char> temp(static_cast<std::size_t>(pos));
75 ifs.seekg(0, std::ios::beg);
76 ifs.read(&temp[0], pos);
77 ifs.close();
78
79 auto bytecode = std::vector<uint8_t>(static_cast<std::size_t>(pos));
80 // TODO would it be faster to memcpy?
81 for (std::size_t i = 0; i < static_cast<std::size_t>(pos); ++i)
82 bytecode[i] = static_cast<uint8_t>(temp[i]);
83 return bytecode;
84 }
85}
86
87#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::vector< uint8_t > readFileAsBytes(const std::string &name)
Helper to read the bytes of a file.
Definition Files.hpp:63