-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_stream.h
More file actions
124 lines (96 loc) · 2.69 KB
/
Copy pathfile_stream.h
File metadata and controls
124 lines (96 loc) · 2.69 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
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
119
120
121
122
123
124
#pragma once
#include "trace.h"
#include <windows.h>
#include <string>
class file_stream
{
public:
file_stream() :
_handle(INVALID_HANDLE_VALUE)
{
}
~file_stream()
{
close();
}
void open(const std::string& path,
DWORD create_mode, DWORD access_mode, DWORD share_mode = 0)
{
close();
_handle = CreateFileA(path.c_str(), access_mode, share_mode,
NULL, create_mode, FILE_ATTRIBUTE_NORMAL, NULL);
if (_handle == INVALID_HANDLE_VALUE)
throw std::exception("file_stream, open file");
}
void close()
{
if (_handle != INVALID_HANDLE_VALUE) {
CloseHandle(_handle);
_handle = INVALID_HANDLE_VALUE;
}
}
DWORD read(void* data, DWORD count)
{
check_handle();
DWORD read_count = 0;
if (ReadFile(_handle, data, count, &read_count, NULL))
return read_count;
throw std::exception("file_stream, read file");
}
DWORD write(const void* data, DWORD count)
{
check_handle();
DWORD write_count = 0;
if (WriteFile(_handle, data, count, &write_count, NULL))
return write_count;
throw std::exception("file_stream, write file");
}
DWORD seek(LONG length, DWORD method)
{
check_handle();
DWORD ret = SetFilePointer(_handle, length, NULL, method);
if (ret != INVALID_SET_FILE_POINTER)
return ret;
throw std::exception("file_stream, seek");
}
DWORD size()
{
check_handle();
DWORD ret = GetFileSize(_handle, NULL);
if (ret != INVALID_FILE_SIZE)
return ret;
throw std::exception("file_stream, size");
}
DWORD position()
{
check_handle();
DWORD ret = SetFilePointer(_handle, 0, NULL, FILE_CURRENT);
if (ret != INVALID_SET_FILE_POINTER)
return ret;
throw std::exception("file_stream, position");
}
void flush()
{
check_handle();
if (FlushFileBuffers(_handle))
return;
throw std::exception("file_stream, flush");
}
void truncate()
{
check_handle();
if (SetEndOfFile(_handle))
return;
throw std::exception("file_stream, truncate");
}
private:
void check_handle()
{
if (_handle == INVALID_HANDLE_VALUE)
throw std::exception("file_stream, invalid handle");
}
HANDLE _handle;
private:
file_stream(const file_stream&);
file_stream& operator=(const file_stream&);
};