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.1
6 * @date 2021-11-25
7 *
8 * @copyright Copyright (c) 2021
9 *
10 */
11
12#ifndef INCLUDE_ARK_FILES_HPP
13#define INCLUDE_ARK_FILES_HPP
14
15#include <string>
16#include <fstream>
17#include <streambuf>
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 // 11
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.c_str());
51 // admitting the file exists
52 return std::string(
53 (std::istreambuf_iterator<char>(f)),
54 std::istreambuf_iterator<char>());
55 }
56
57 /**
58 * @brief Get the directory from a path
59 *
60 * @param path
61 * @return std::string
62 */
63 inline std::string getDirectoryFromPath(const std::string& path)
64 {
65 return (std::filesystem::path(path)).parent_path().string();
66 }
67
68 /**
69 * @brief Get the filename from a path
70 *
71 * @param path
72 * @return std::string
73 */
74 inline std::string getFilenameFromPath(const std::string& path)
75 {
76 return (std::filesystem::path(path)).filename().string();
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 std::filesystem::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::string getDirectoryFromPath(const std::string &path)
Get the directory from a path.
Definition: Files.hpp:63
std::string getFilenameFromPath(const std::string &path)
Get the filename from a path.
Definition: Files.hpp:74