-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.hpp
118 lines (102 loc) · 2.02 KB
/
file.hpp
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#pragma once
// file.hpp - win32 file class (include <windows.h>)
//
// v1.2 Reallocation implemented.
// v1.1 handle failures, operator char*()
// v1.0 working version, little error handling
struct File
{
File()
{
Data = 0;
Free();
}
DWORD GetFileSize()
{
return this->FileSize;
}
bool SetFileSize(DWORD NewFileSize)
{
if (NewFileSize == FileSize)
return true;
// release any allocated memory
if (NewFileSize == 0)
{
Free();
return true;
}
// allocate new memory
if (FileSize == 0) {
Data = ::HeapAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, NewFileSize);
if (Data)
{
this->FileSize = NewFileSize;
return true;
}
return false;
}
// Reallocate memory to match the new requirements
LPVOID NewData = ::HeapReAlloc(::GetProcessHeap(), HEAP_ZERO_MEMORY, Data, NewFileSize);
if (NewData)
{
this->FileSize = NewFileSize;
this->Data = NewData;
return true;
}
return false;
}
bool Write(LPCTSTR fname)
{
if (FileSize == 0)
return false;
HANDLE file = ::CreateFile(fname, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0);
if (file != INVALID_HANDLE_VALUE)
{
DWORD written = 0;
::WriteFile(file, Data, FileSize, &written, 0);
::CloseHandle(file);
}
return false;
}
bool Read(LPCTSTR fname)
{
//Free();
HANDLE file = ::CreateFile(fname, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
if (file != INVALID_HANDLE_VALUE)
{
DWORD fSize = ::GetFileSize(file, 0);
if (this->SetFileSize(fSize))
{
DWORD read;
::ReadFile(file, Data, fSize, &read, 0);
::CloseHandle(file);
if (read == fSize)
return true;
else
Free();
}
else
{
::CloseHandle(file);
}
}
return false;
}
void Free()
{
if (Data) ::HeapFree(::GetProcessHeap(), 0, Data);
Data = 0;
FileSize = 0;
}
inline operator char*()
{
return (char*) Data;
}
~File()
{
Free();
}
LPVOID Data;
private:
DWORD FileSize;
};