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 * @date 2024-07-09
6 *
7 * @copyright Copyright (c) 2021-2025
8 *
9 */
10
11#ifndef INCLUDE_ARK_FILES_HPP
12#define INCLUDE_ARK_FILES_HPP
13
14#include <string>
15#include <vector>
16#include <fstream>
17#include <filesystem>
18
19namespace Ark::Utils
20{
21 /**
22 * @brief Checks if a file exists
23 *
24 * @param name the file name
25 * @return true on success
26 * @return false on failure
27 */
28 inline bool fileExists(const std::string& name) noexcept
29 {
30 try
31 {
32 return std::filesystem::exists(std::filesystem::path(name));
33 }
34 catch (const std::filesystem::filesystem_error&)
35 {
36 // if we met an error than we most likely fed an invalid path
37 return false;
38 }
39 }
40
41 /**
42 * @brief Helper to read a file
43 *
44 * @param name the file name
45 * @return std::string
46 */
47 inline std::string readFile(const std::string& name)
48 {
49 std::ifstream f(name);
50 // admitting the file exists
51 return {
52 (std::istreambuf_iterator<char>(f)),
53 std::istreambuf_iterator<char>()
54 };
55 }
56
57 /**
58 * @brief Helper to read the bytes of a file
59 * @param name filename
60 * @return std::vector<uint8_t>
61 */
62 inline std::vector<uint8_t> readFileAsBytes(const std::string& name)
63 {
64 // admitting the file exists
65 std::ifstream ifs(name, std::ios::binary | std::ios::ate);
66 if (!ifs.good())
67 return std::vector<uint8_t> {};
68
69 const auto pos = ifs.tellg();
70 if (pos == 0)
71 return {};
72 // reserve appropriate number of bytes
73 std::vector<char> temp(static_cast<std::size_t>(pos));
74 ifs.seekg(0, std::ios::beg);
75 ifs.read(&temp[0], pos);
76 ifs.close();
77
78 auto bytecode = std::vector<uint8_t>(static_cast<std::size_t>(pos));
79 for (std::size_t i = 0; i < static_cast<std::size_t>(pos); ++i)
80 bytecode[i] = static_cast<uint8_t>(temp[i]);
81 return bytecode;
82 }
83}
84
85#endif
std::string readFile(const std::string &name)
Helper to read a file.
Definition Files.hpp:47
bool fileExists(const std::string &name) noexcept
Checks if a file exists.
Definition Files.hpp:28
std::vector< uint8_t > readFileAsBytes(const std::string &name)
Helper to read the bytes of a file.
Definition Files.hpp:62