| 6 |
| * Copyright Nikolai Kudashov, 2015. |
| 7 | */ |
| 8 |
| 9 | #include "Config.h" |
| 10 | #include "ConnectionsManager.h" |
| 11 | #include "FileLog.h" |
| 12 | #include "BuffersStorage.h" |
| 13 |
| 14 | Config::Config(std::string fileName) { |
| 15 | configPath = ConnectionsManager::getInstance().currentConfigPath + fileName; |
| 16 | backupPath = configPath + ".bak"; |
| 17 | FILE *backup = fopen(backupPath.c_str(), "rb"); |
| 18 | if (backup != nullptr) { |
| 19 | remove(configPath.c_str()); |
| 20 | rename(backupPath.c_str(), configPath.c_str()); |
| 21 | fclose(backup); |
| 22 | } |
| 23 | } |
| 24 |
| 25 | NativeByteBuffer *Config::readConfig() { |
| 26 | NativeByteBuffer *buffer = nullptr; |
| 27 | FILE *file = fopen(configPath.c_str(), "rb"); |
| 28 | if (file != nullptr) { |
| 29 | fseek(file, 0, SEEK_END); |
| 30 | long fileSize = ftell(file); |
| 31 | fseek(file, 0, SEEK_SET); |
| 32 | uint32_t size = 0; |
| 33 | int bytesRead = fread(&size, sizeof(uint32_t), 1, file); |
| 34 | DEBUG_D("Config(%p, %s) load, size = %u", this, configPath.c_str(), size); |
| 35 | if (bytesRead > 0 && size > 0 && (int32_t) size < fileSize) { |
| 36 | buffer = BuffersStorage::getInstance().getFreeBuffer(size); |
| 37 | if (fread(buffer->bytes(), sizeof(uint8_t), size, file) != size) { |
| 38 | buffer->reuse(); |
| 39 | buffer = nullptr; |
| 40 | } |
| 41 | } |
| 42 | fclose(file); |
| 43 | } |
| 44 | return buffer; |
| 45 | } |
| 46 |
| 47 | void Config::writeConfig(NativeByteBuffer *buffer) { |
| 48 | FILE *file = fopen(configPath.c_str(), "rb"); |
| 49 | FILE *backup = fopen(backupPath.c_str(), "rb"); |
| 50 | bool error = false; |
| 51 | if (file != nullptr) { |
| 52 | if (backup == nullptr) { |
| 53 | fclose(file); |
| 54 | if (rename(configPath.c_str(), backupPath.c_str()) != 0) { |
| 55 | DEBUG_E("Config(%p) unable to rename file %s to backup file %s", this, configPath.c_str(), backupPath.c_str()); |
| 56 | error = true; |
| 57 | } |
| 58 | } else { |
| 59 | fclose(file); |
| 60 | fclose(backup); |
| 61 | remove(configPath.c_str()); |
| 62 | } |
| 63 | } |
| 64 | if (error) { |
| 65 | return; |
| 66 | } |
| 67 | file = fopen(configPath.c_str(), "wb"); |
| 68 | if (file == nullptr) { |
| 69 | return; |
| 70 | } |
| 71 | uint32_t size = buffer->position(); |
| 72 | if (fwrite(&size, sizeof(uint32_t), 1, file) == 1) { |
| 73 | if (fwrite(buffer->bytes(), sizeof(uint8_t), size, file) != size) { |
| 74 | error = true; |
| 75 | } |
| 76 | } else { |
| 77 | error = true; |
| 78 | } |
| 79 | fclose(file); |
| 80 | if (error) { |
| 81 | remove(configPath.c_str()); |
| 82 | } else { |
| 83 | remove(backupPath.c_str()); |
| 84 | } |
| 85 | } |
| 86 |