This repository was archived by the owner on Feb 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileUtils.cpp
More file actions
88 lines (70 loc) · 2.07 KB
/
FileUtils.cpp
File metadata and controls
88 lines (70 loc) · 2.07 KB
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
#include "FileUtils.h"
void FileUtils::MoveCursorTo(const std::streampos position, std::ifstream& file)
{
file.seekg(position, std::ifstream::beg);
}
void FileUtils::MoveCursorTo(const std::streampos position, std::ofstream& file)
{
file.seekp(position, std::ofstream::beg);
}
void FileUtils::MoveCursorToTheEnd(std::ifstream& file)
{
file.seekg(0, std::ifstream::end);
}
void FileUtils::MoveCursorToTheEnd(std::ofstream& file)
{
file.seekp(0, std::ofstream::end);
}
std::string FileUtils::GetFilenameWithoutExtenstion(const std::string& filename)
{
return filename.substr(0, filename.find_last_of('.'));
}
std::string FileUtils::GetFilenameWithoutPathAndExtenstion(const std::string& filename)
{
const auto cleanFilename = GetFilenameWithoutExtenstion(filename);
return cleanFilename.substr(cleanFilename.find_last_of('/') + 1, cleanFilename.length());
}
size_t FileUtils::GetFileLength(std::ifstream& file)
{
const std::streampos previousPosition = file.tellg();
MoveCursorToTheEnd(file);
const std::streampos length = file.tellg();
MoveCursorTo(previousPosition, file);
return length;
}
size_t FileUtils::GetFileLength(std::ofstream& file)
{
const std::streampos previousPosition = file.tellp();
MoveCursorToTheEnd(file);
const std::streampos length = file.tellp();
MoveCursorTo(previousPosition, file);
return length;
}
void FileUtils::ChangeFileExtension(const std::string& filename, const std::string& newExtenstion, const bool removeOldFileIfExists)
{
const std::string newFile = GetFilenameWithoutExtenstion(filename) + newExtenstion;
if (removeOldFileIfExists)
{
if (std::remove(newFile.c_str()) != 0)
{
// Fail means that the file didn't exist
}
}
if (std::rename(filename.c_str(), newFile.c_str()) != 0)
{
throw std::runtime_error("Failed to rename file!");
}
}
void FileUtils::CreateFile(const std::string& filename, bool recreateIfExists)
{
std::ifstream file;
if (recreateIfExists)
{
file = std::ifstream(filename, std::ifstream::binary);
}
else
{
file = std::ifstream(filename, std::ifstream::binary | std::ifstream::app);
}
file.close();
}