Информация об изменениях

Сообщение Re: Как в одну строку кода прочитать содержимое файла в масс от 02.01.2024 13:14

Изменено 02.01.2024 14:14 rg45

Re: Как в одну строку кода прочитать содержимое файла в массив?
Здравствуйте, Kluev, Вы писали:

K>есть ли в std аналог File.ReadAllBytes()?


Готового нету, но можно написать самому:

#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdint>

std::vector<uint8_t> read_all_bytes(const std::string& path)
{
   std::vector<uint8_t> bytes;
   std::basic_ifstream<uint8_t> input(path.c_str(), std::ios_base::in | std::ios_base::binary);
   std::copy(
      std::istreambuf_iterator<uint8_t>(input),
      std::istreambuf_iterator<uint8_t>(),
      std::back_inserter(bytes)
   );
   return bytes;
}

void save_all_bytes(const std::vector<uint8_t>& bytes, const std::string& path)
{
   std::basic_ofstream<uint8_t> output(path.c_str(), std::ios_base::out | std::ios_base::binary);
   std::copy(bytes.begin(), bytes.end(), std::ostreambuf_iterator<uint8_t>(output));
}
Re: Как в одну строку кода прочитать содержимое файла в масс
Здравствуйте, Kluev, Вы писали:

K>есть ли в std аналог File.ReadAllBytes()?


Готового нету, но можно написать самому (исправлено
Автор: Voivoid
Дата: 02.01 16:58
):


#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdint>

std::vector<uint8_t> read_all_bytes(const std::string& path)
{
   std::basic_ifstream<uint8_t> input(path.c_str(), std::ios_base::in | std::ios_base::binary);
   return { std::istreambuf_iterator<uint8_t>(input), std::istreambuf_iterator<uint8_t>() };
}

void save_all_bytes(const std::vector<uint8_t>& bytes, const std::string& path)
{
   std::basic_ofstream<uint8_t> output(path.c_str(), std::ios_base::out | std::ios_base::binary);
   std::copy(bytes.begin(), bytes.end(), std::ostreambuf_iterator<uint8_t>(output));
}