-
Notifications
You must be signed in to change notification settings - Fork 18
/
confighandler.cpp
81 lines (70 loc) · 1.94 KB
/
confighandler.cpp
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
#include "confighandler.h"
#include <QFile>
#include <QDebug>
void ConfigHandler::setConfigFilename(const QString &filename)
{
this->filename = filename;
}
QString ConfigHandler::configFilename() const
{
return this->filename;
}
bool ConfigHandler::changeSetting(const char *setting, const int value) const
{
bool found = false;
QFile file(filename);
char buf[1024];
QByteArray line;
qint64 len, offset;
if (!file.open(QFile::ReadWrite)) {
qDebug() << "Failed to open" << filename;
return false;
}
while (!found && !file.atEnd()) {
// Read next line into memory
len = file.readLine(buf, sizeof(buf));
if (len <= 0) break;
line = QByteArray(buf);
if (line.startsWith(setting)) {
found = true;
offset = file.pos() - len;
}
}
if (found) {
QByteArray restOfFile;
// Modify line
int idx = line.indexOf('=');
line = line.left(idx+1);
line.append(QByteArray::number(value) + "\n");
// Store rest of file in memory (potentially dangerous!)
restOfFile.append(line);
while (!file.atEnd()) {
// Read next line into memory
len = file.read(buf, sizeof(buf));
if (len < 0) {
found = false;
break;
}
restOfFile.append(buf, len);
}
// Restore file with modified line
file.seek(offset);
len = file.write(restOfFile);
if (len != restOfFile.size()) {
qDebug() << "Wrote" << len << " bytes. Should have been" << restOfFile.size();
found = false;
}
}
// Append setting
else {
file.seek(file.size());
line = QByteArray(setting);
line += "=";
line += QByteArray::number(value);
line += "\n";
file.write(line);
found = true;
}
file.close();
return found;
}