tgbotxx  1.1.6.9
Telegram Bot C++ Library
FileUtils.hpp
Go to the documentation of this file.
1 #pragma once
2 #include <filesystem>
3 #include <fstream>
4 #include <functional>
5 #include <string>
6 #include <tgbotxx/Exception.hpp>
7 #include <vector>
8 namespace fs = std::filesystem;
9 
10 namespace tgbotxx {
12  namespace FileUtils {
15  [[nodiscard]] static std::string read(const fs::path& filename) {
16  if (std::ifstream ifs{filename, std::ios::ate | std::ios::binary}) {
17  std::string buffer(ifs.tellg(), '\000');
18  ifs.seekg(0, std::ios::beg);
19  ifs.read(buffer.data(), buffer.size());
20  ifs.close();
21  return buffer;
22  } else {
23  throw Exception("No such file " + filename.string());
24  }
25  }
26 
29  [[nodiscard]] static std::vector<std::string> readLines(const fs::path& filename) {
30  if (std::ifstream ifs{filename, std::ios::binary}) {
31  std::vector<std::string> lines{};
32  std::string line{};
33  while (std::getline(ifs, line)) {
34  lines.push_back(line);
35  }
36  ifs.close();
37  return lines;
38  } else {
39  throw Exception("No such file " + filename.string());
40  }
41  }
42 
45  static void readChunks(const fs::path& filename, const std::size_t maxChunkSize, const std::function<void(std::vector<std::uint8_t>&&)>& callback) {
46  if (std::ifstream ifs{filename, std::ios::binary}) {
47  while (!ifs.eof()) {
48  std::vector<std::uint8_t> chunk(maxChunkSize, '\000');
49  ifs.read(reinterpret_cast<char *>(chunk.data()), chunk.size());
50 
51  // resize chunk if we read bytes less than max_chunk_size
52  const auto bytes_read = static_cast<std::size_t>(ifs.gcount());
53  if (bytes_read < maxChunkSize)
54  chunk.resize(bytes_read);
55 
56  // serve chunk
57  callback(std::move(chunk));
58  }
59  ifs.close();
60  } else {
61  throw Exception("No such file " + filename.string());
62  }
63  }
64 
67  static void write(const fs::path& filename, const std::string& buffer) {
68  if (std::ofstream ofs{filename, std::ios::binary}) {
69  ofs.write(buffer.data(), buffer.size());
70  ofs.close();
71  } else {
72  throw Exception("Failed to write file " + filename.string());
73  }
74  }
75 
76  }
77 }
tgbotxx::Exception
Definition: Exception.hpp:91
static void write(const fs::path &filename, const std::string &buffer)
Write buffer string to a new file.
Definition: FileUtils.hpp:67
static std::string read(const fs::path &filename)
Read entire file into an std::string.
Definition: FileUtils.hpp:15
static std::vector< std::string > readLines(const fs::path &filename)
Read entire file lines into std::vector<std::string>
Definition: FileUtils.hpp:29
static void readChunks(const fs::path &filename, const std::size_t maxChunkSize, const std::function< void(std::vector< std::uint8_t > &&)> &callback)
Read file chunk by chunk.
Definition: FileUtils.hpp:45
Definition: Api.hpp:14