-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.h
executable file
·106 lines (85 loc) · 2.53 KB
/
file.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
99
100
101
102
103
104
105
106
#pragma once
#include <cassert>
#include <windows.h>
// A minimal HFILE wrapper
// It's far from being general enough for real-world use,
// but for our simple needs will do.
class CVFile {
HANDLE m_hFile;
CVFile(HANDLE hf): m_hFile(hf) { }
public:
~CVFile() {
assert( m_hFile != INVALID_HANDLE_VALUE );
::CloseHandle(m_hFile);
}
enum OpenMode {
omRead = GENERIC_READ,
omWrite = GENERIC_WRITE,
omReadWrite = GENERIC_READ | GENERIC_WRITE
};
enum SeekMode {
smSet = FILE_BEGIN,
smCur = FILE_CURRENT,
smEnd = FILE_END
};
enum OpenPolicy {
opExisting = OPEN_EXISTING,
opNew = CREATE_NEW,
opAlways = OPEN_ALWAYS,
opCreateNew = CREATE_ALWAYS,
opTruncate = TRUNCATE_EXISTING,
opInvalid = ~0
};
friend CVFile *FileOpen(const char *pchFilename, OpenMode om = omRead, OpenPolicy = opInvalid);
HRESULT Read(void *pData, DWORD dwCount) {
assert( m_hFile != INVALID_HANDLE_VALUE );
DWORD dwRead;
BOOL bResult;
bResult = ::ReadFile(m_hFile, pData, dwCount, &dwRead, 0);
return bResult ? S_OK : S_FALSE;
}
HRESULT Write(void *pData, DWORD dwCount) {
assert( m_hFile != INVALID_HANDLE_VALUE );
DWORD dwRead;
BOOL bResult;
bResult = ::WriteFile(m_hFile, pData, dwCount, &dwRead, 0);
return bResult ? S_OK : S_FALSE;
}
DWORD GetFileSize() {
assert( m_hFile != INVALID_HANDLE_VALUE );
return ::GetFileSize(m_hFile, 0);
}
DWORD GetFilePointer() {
assert( m_hFile != INVALID_HANDLE_VALUE );
return ::SetFilePointer(m_hFile, 0, 0, smCur);
}
DWORD Seek(LONG lOffset, SeekMode sm = smCur) {
assert( m_hFile != INVALID_HANDLE_VALUE );
return ::SetFilePointer(m_hFile, lOffset, 0, sm);
}
};
inline CVFile *FileOpen(const char *pchFilename, CVFile::OpenMode om, CVFile::OpenPolicy op)
{
HANDLE hFile;
if( op == CVFile::opInvalid ) {
switch( om ) {
case CVFile::omRead : op = CVFile::opExisting; break;
case CVFile::omWrite : op = CVFile::opCreateNew; break;
case CVFile::omReadWrite : op = CVFile::opAlways; break;
default : assert(!"Invalid open mode");
}
}
hFile = ::CreateFile(
pchFilename, // Filename
(DWORD)om, // Desired Access
0, // Share Mode - don't share
0, // security - no security
OPEN_ALWAYS, // creation - create always
0, // file attributes - normal
0 // file template - none
);
if( hFile == INVALID_HANDLE_VALUE ) {
return 0;
}
return new CVFile(hFile);
}