---
title: llarp/util/file.hpp

---

# llarp/util/file.hpp



## Namespaces

| Name           |
| -------------- |
| **[llarp](Namespaces/namespacellarp.md)** <br>[crypto.hpp] |
| **[llarp::util](Namespaces/namespacellarp_1_1util.md)**  |

## Classes

|                | Name           |
| -------------- | -------------- |
| struct | **[llarp::util::FileHash](Classes/structllarp_1_1util_1_1FileHash.md)**  |




## Source code

```cpp
#pragma once
#include "fs.hpp"

#include <optional>
#include <set>
#include <string>
#include <string_view>

#ifndef _MSC_VER
#include <dirent.h>
#endif

namespace llarp::util
{
  std::string
  slurp_file(const fs::path& filename);

  size_t
  slurp_file(const fs::path& filename, char* buffer, size_t buffer_size);

  template <
      typename Char,
      std::enable_if_t<sizeof(Char) == 1 and not std::is_same_v<Char, char>, int> = 1>
  inline size_t
  slurp_file(const fs::path& filename, Char* buffer, size_t buffer_size)
  {
    return slurp_file(filename, reinterpret_cast<char*>(buffer), buffer_size);
  }

  void
  dump_file(const fs::path& filename, std::string_view contents);

  template <typename Char, std::enable_if_t<sizeof(Char) == 1, int> = 0>
  inline void
  dump_file(const fs::path& filename, const Char* buffer, size_t buffer_size)
  {
    return dump_file(
        filename, std::string_view{reinterpret_cast<const char*>(buffer), buffer_size});
  }

  struct FileHash
  {
    size_t
    operator()(const fs::path& f) const
    {
      std::hash<std::string> h;
      return h(f.string());
    }
  };

  using error_code_t = std::error_code;

  error_code_t
  EnsurePrivateFile(fs::path pathname);

  template <typename T>
  std::optional<T>
  OpenFileStream(fs::path pathname, std::ios::openmode mode)
  {
    if (EnsurePrivateFile(pathname))
      return {};
    return std::make_optional<T>(pathname, mode);
  }

  template <typename PathVisitor>
  static void
  IterDir(const fs::path& path, PathVisitor visit)
  {
    DIR* d = opendir(path.string().c_str());
    if (d == nullptr)
      return;
    struct dirent* ent = nullptr;
    std::set<fs::path> entries;
    do
    {
      ent = readdir(d);
      if (not ent)
        break;
      if (ent->d_name[0] == '.')
        continue;
      entries.emplace(path / fs::path{ent->d_name});
    } while (ent);
    closedir(d);

    for (const auto& p : entries)
    {
      if (not visit(p))
        return;
    }
  }

}  // namespace llarp::util
```


-------------------------------

Updated on 2023-01-30 at 17:55:38 +0000
