-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_file_op.h
72 lines (64 loc) · 1.58 KB
/
simple_file_op.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
#ifndef ZZ_STRING_TO_FILE
#define ZZ_STRING_TO_FILE
#include <iostream>
#include <fstream>
using namespace std;
//only append .
class FileWriter {
public:
FileWriter(const string& name) : ofstr_(name.c_str(), ios::app | ios::binary) {}
template<class T>
void WriteByType(const T& tmp) {
ofstr_.write((const char*)&tmp, sizeof(T));
ofstr_.flush();
}
void WriteString(const string& tmp) {
WriteCString(tmp.c_str(), tmp.size());
ofstr_.flush();
}
void WriteCString(const char *p, const size_t len) {
WriteByType<size_t>(len);
ofstr_.write(p, len);
ofstr_.flush();
}
~FileWriter() {ofstr_.close();}
ofstream ofstr_;
};
//only orderly read ...
class FileReader {
public:
FileReader(const string& name) : ifstr_(name.c_str(), ios::app) {}
template<class T>
bool ReadByType(T& ret) {
ifstr_.read((char *)&ret, sizeof(T));
if (ifstr_.eof()) {
return false;
}
return true;
}
bool ReadString(string& ret) {
size_t len = 0;
if(!ReadByType<size_t>(len)) {
return false;
}
ret.resize(len);
ifstr_.read((char *)ret.c_str(), len);
if (ifstr_.eof()) {
return false;
}
return true;
}
~FileReader() {ifstr_.close();}
ifstream ifstr_;
size_t cur_pos = 0;
};
//int main()
//{
// FileWriter writer("test.txt");
// writer.WriteString("nihao");
// FileReader reader("test.txt");
// string str;
// reader.ReadString(str);
// return 0;
//}
#endif