summaryrefslogtreecommitdiff
path: root/ZAPDUtils/Utils/File.h
blob: bf2bb694eb3fc8e16e4deca40b0fddcf749aecf1 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#pragma once

#include <fstream>
#include <string>
#include <vector>
#include "Directory.h"
#include "Utils/StringHelper.h"

class File
{
public:
	static bool Exists(const fs::path& filePath)
	{
		std::ifstream file(filePath, std::ios::in | std::ios::binary | std::ios::ate);
		return file.good();
	}

	static std::vector<uint8_t> ReadAllBytes(const fs::path& filePath)
	{
		std::ifstream file(filePath, std::ios::in | std::ios::binary | std::ios::ate);
		int32_t fileSize = (int32_t)file.tellg();
		file.seekg(0);
		char* data = new char[fileSize];
		file.read(data, fileSize);
		std::vector<uint8_t> result = std::vector<uint8_t>(data, data + fileSize);
		delete[] data;
		file.close();

		return result;
	};

	static std::string ReadAllText(const fs::path& filePath)
	{
		std::ifstream file(filePath, std::ios::in | std::ios::binary | std::ios::ate);
		if (!file.is_open())
			return "";
		int32_t fileSize = (int32_t)file.tellg();
		file.seekg(0);
		char* data = new char[fileSize + 1];
		memset(data, 0, fileSize + 1);
		file.read(data, fileSize);
		std::string str = std::string((const char*)data);
		delete[] data;
		file.close();

		return str;
	};

	static std::vector<std::string> ReadAllLines(const fs::path& filePath)
	{
		std::string text = ReadAllText(filePath);
		std::vector<std::string> lines = StringHelper::Split(text, "\n");

		return lines;
	};

	static void WriteAllBytes(const fs::path& filePath, const std::vector<uint8_t>& data)
	{
		std::ofstream file(filePath, std::ios::binary);
		file.write((char*)data.data(), data.size());
		file.close();
	};

	static void WriteAllBytes(const std::string& filePath, const std::vector<char>& data)
	{
		std::ofstream file(filePath, std::ios::binary);
		file.write((char*)data.data(), data.size());
		file.close();
	};

	static void WriteAllBytes(const std::string& filePath, const char* data, int dataSize)
	{
		std::ofstream file(filePath, std::ios::binary);
		file.write((char*)data, dataSize);
		file.close();
	};

	static void WriteAllText(const fs::path& filePath, const std::string& text)
	{
		std::ofstream file(filePath, std::ios::out);
		file.write(text.c_str(), text.size());
		file.close();
	}
};