| 1 | /* |
| 2 | * Descent 3 |
| 3 | * Copyright (C) 2024 Parallax Software |
| 4 | * |
| 5 | * This program is free software: you can redistribute it and/or modify |
| 6 | * it under the terms of the GNU General Public License as published by |
| 7 | * the Free Software Foundation, either version 3 of the License, or |
| 8 | * (at your option) any later version. |
| 9 | * |
| 10 | * This program is distributed in the hope that it will be useful, |
| 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | * GNU General Public License for more details. |
| 14 | * |
| 15 | * You should have received a copy of the GNU General Public License |
| 16 | * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | |
| 19 | #include <cstdarg> |
| 20 | #include <cstdio> |
| 21 | |
| 22 | #include "logfile.h" |
| 23 | |
| 24 | #ifdef _DEBUG |
| 25 | static bool log_enable = true; |
| 26 | #else |
| 27 | static bool log_enable = false; |
| 28 | #endif |
| 29 | |
| 30 | void log_Enable(bool enable) { log_enable = true; } |
| 31 | |
| 32 | void log_Disable() { log_enable = false; } |
| 33 | |
| 34 | logfile::logfile() { fp = NULL; } |
| 35 | |
| 36 | logfile::~logfile() { end(); } |
| 37 | |
| 38 | // restarts the logfile (opens a new one.) |
| 39 | void logfile::start(const char *fname, const char *longname) { |
| 40 | if (log_enable) { |
| 41 | try { |
| 42 | fp = (FILE *)fopen(fname, "wt"); |
| 43 | logfile::printf("%s\n", longname); |
| 44 | } catch (...) { |
| 45 | fp = NULL; |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | void logfile::end() { |
| 51 | if (fp) { |
| 52 | try { |
| 53 | fclose((FILE *)fp); |
| 54 | fp = NULL; |
| 55 | } catch (...) { |
| 56 | fp = NULL; |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | void logfile::printf(const char *fmt, ...) { |
| 62 | if (fp && fmt) { |
| 63 | char msg[256]; |
| 64 | std::va_list arglist; |
| 65 | va_start(arglist, fmt); |
| 66 | std::vsnprintf(msg, sizeof(msg), fmt, arglist); |
| 67 | va_end(arglist); |
| 68 | |
| 69 | logfile::puts(msg); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | void logfile::puts(const char *msg) { |
| 74 | if (fp && msg) { |
| 75 | try { |
| 76 | fputs(msg, (FILE *)fp); |
| 77 | } catch (...) { |
| 78 | end(); |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | void logfile::update() { |
| 84 | if (fp) { |
| 85 | try { |
| 86 | fflush((FILE *)fp); |
| 87 | } catch (...) { |
| 88 | end(); |
| 89 | } |
| 90 | } |
| 91 | } |