-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserdao.cpp
More file actions
105 lines (91 loc) · 1.75 KB
/
userdao.cpp
File metadata and controls
105 lines (91 loc) · 1.75 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
#define _CRT_SECURE_NO_WARNINGS
#include "userdao.h"
Userdao::Userdao() {
}
Userdao::~Userdao() {
}
std::string Userdao::readContentByUserid(std::string fileName, int id) {
std::ifstream in;
char line[1024] = { '\0' };
in.open(fileName);
int i = 0;
std::string result;
while (in.getline(line, sizeof(line)))
{
if (i++ != id) {
continue;
}
result = charToStr(line);
return result;
}
in.close();
return "user not exist!";
}
void Userdao::modifyContentByUserid(std::string fileName, int id, std::string content) {
std::ifstream in;
char line[1024] = { '\0' };
in.open(fileName);
int i = 0;
std::string tempStr;
while (in.getline(line, sizeof(line)))
{
if (i == id)
{
tempStr += std::to_string(id) + content;
}
else
{
tempStr += charToStr(line);
}
tempStr += '\n';
i++;
}
in.close();
std::ofstream out;
out.open(fileName);
out.flush();
out << tempStr;
out.close();
}
int Userdao::addUser(std::string fileName, std::string content) {
std::fstream file;
int ch;
file.open(fileName, std::ios::in);
ch = file.get(); //试图去读一个字符
if (file.eof()) //或 if ( ch==EOF ) //一个字符都未读到,表示文件为空
{
writeContent(fileName, "0");
}
file.close();
std::ifstream in;
char line[1024] = { '\0' };
int i = 0, newid = 0;
in.open(fileName);
std::string tempStr = "";
while (in.getline(line, sizeof(line)))
{
// 更新计数器
if (i == 0) {
newid = atoi(charToStr(line).c_str());
newid++;
tempStr += std::to_string(newid);
}
else
{
tempStr += charToStr(line);
}
tempStr += '\n';
i++;
}
tempStr += std::to_string(newid);
tempStr += "#";
tempStr += content;
tempStr += "\n";
in.close();
std::ofstream out;
out.open(fileName);
out.flush();
out << tempStr;
out.close();
return newid;
}