/
FileUtils.h
98 lines (78 loc) · 2.14 KB
/
FileUtils.h
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#pragma once
#include <string>
#include <fstream>
#include "ifilesystem.h"
#include "os/fs.h"
#include "string/replace.h"
namespace test
{
class BackupCopy
{
private:
fs::path _originalFile;
fs::path _backupFile;
public:
BackupCopy(const fs::path& originalFile) :
_originalFile(originalFile)
{
_backupFile = _originalFile;
_backupFile.replace_extension("bak");
if (fs::exists(_backupFile))
{
fs::remove(_backupFile);
}
fs::copy(_originalFile, _backupFile);
}
~BackupCopy()
{
fs::remove(_originalFile);
fs::rename(_backupFile, _originalFile);
}
// Restore the original file, keep the backup
void restoreNow()
{
fs::remove(_originalFile);
fs::copy(_backupFile, _originalFile);
}
};
namespace algorithm
{
// Writes the given contents to the given path, overwriting it
inline void replaceFileContents(const std::string& path, const std::string& contents)
{
std::ofstream stream(path, std::ofstream::out);
stream << contents;
stream.flush();
stream.close();
}
// Loads the entire text from the given vfs file into a string
inline std::string loadTextFromVfsFile(const std::string& vfsPath)
{
auto file = GlobalFileSystem().openTextFile(vfsPath);
if (!file)
{
return std::string();
}
std::stringstream textStream;
std::istream mapStream(&file->getInputStream());
textStream << mapStream.rdbuf();
textStream.flush();
return textStream.str();
}
// Returns the text contents of the given file
inline std::string loadFileToString(const fs::path& path)
{
std::stringstream contentStream;
std::ifstream input(path);
contentStream << input.rdbuf();
return contentStream.str();
}
// True if the file (full physical path) contains the given text (ignoring CRLF vs. LF line break differences)
inline bool fileContainsText(const fs::path& path, const std::string& textToFind)
{
auto rawContents = loadFileToString(path);
auto contents = string::replace_all_copy(rawContents, "\r\n", "\n");
return contents.find(textToFind) != std::string::npos;
}
}
}