From 43c1802f880471c5b69f8c622314827790aad0b8 Mon Sep 17 00:00:00 2001 From: Miquel Sabaté Solà Date: Fri, 26 Sep 2025 23:04:36 +0200 Subject: Initial commit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Miquel Sabaté Solà --- src/print.c | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 src/print.c (limited to 'src/print.c') diff --git a/src/print.c b/src/print.c new file mode 100644 index 0000000..364a20b --- /dev/null +++ b/src/print.c @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +/* + * Copyright (C) 2024-Ω Miquel Sabaté Solà + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include + +#include +#include + +/** + * Prints the current local time into the given @stream. If fetching the current + * local time fails, then it does nothing. + */ +void pr_time(FILE *stream) +{ + time_t current_time = time(NULL); + struct tm *tm_info = NULL; + char buffer[32]; + + if (current_time != (time_t)-1) { + tm_info = localtime(¤t_time); + strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm_info); + fprintf(stream, "[%s] ", buffer); + fflush(stream); + } +} + +void pr_out(bool should_halt, FILE *stream, enum print_type type, const char *const message, ...) +{ + va_list args; + + pr_time(stream); + + fprintf(stream, "pudc ("); + fflush(stream); + + switch (type) { + case debug: + fprintf(stream, "debug"); + break; + case error: + fprintf(stream, "error"); + break; + case info: + default: + fprintf(stream, "info"); + break; + }; + fflush(stream); + + fprintf(stream, "): "); + fflush(stream); + + va_start(args, message); + vfprintf(stream, message, args); + fflush(stream); + va_end(args); + + /* + * 'errno' is quite unreliable, so only deal with it if this was called via + * 'pr_error'. + */ + if (type == error) { + fprintf(stream, ": "); + fflush(stream); + perror(NULL); + fflush(stream); + } else { + fprintf(stream, ".\n"); + fflush(stream); + } + + if (should_halt) { + halt(); + } +} -- cgit v1.2.3