aboutsummaryrefslogtreecommitdiff
path: root/src/util/io_impl.hpp
blob: 14f4ded5f05e498b10be339429e99c8718499cdf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#pragma once

#include "io.hpp"

#include "errors/io.hpp"

#include <fstream>

template <typename ContainerType>
requires Container<ContainerType> && HasPushBack<ContainerType> &&
	std::same_as<typename ContainerType::value_type, std::string>
auto read_file_lines(const std::filesystem::path &path) -> ContainerType
{
	if (!std::filesystem::exists(path))
	{
		throw NoSuchFileOrDirectoryError(path);
	}

	const auto file_status = std::filesystem::status(path);

	const auto file_type = file_status.type();

	if (file_type != std::filesystem::file_type::regular)
	{
		throw WrongFileTypeError(path, std::filesystem::file_type::regular, file_type);
	}

	auto file = std::ifstream();

	file.open(path);

	if (!file.is_open())
	{
		throw FileNotOpenError(path);
	}

	auto content_lines = ContainerType();

	while (file)
	{
		auto line = std::string();
		std::getline(file, line);

		std::erase(line, '\r');

		content_lines.push_back(line);
	}

	if (!content_lines.empty() && content_lines.back().empty())
	{
		content_lines.pop_back();
	}

	return content_lines;
}