This is a piece of C89 code testing a function titled logging_function()
, which takes two arguments and uses them to log a bit of information.
In this case, the first argument to the function is the string to be logged, and the second argument is a string holding a path in a filesystem to a log file. The first string is printed, with a timestamp, to stdout and the log file.
Note: although yes input on the main()
function would be wonderful, I'd love it if you gave thoughts on the function logging_function()
itself.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
typedef struct tm tm;
int logging_function(char input_string[], char log_file_string[])
{
/*Initializations.*/
char output_string[32767];
FILE* log_file_stream;
time_t current_time_epoch_format;
tm* current_time_calandar_format;
/*Creating timestamp in output string, amending first argument to output string, and logging.*/
if ((strlen(input_string) + 23) > 32767) return EXIT_FAILURE;
if ((current_time_epoch_format = time(¤t_time_epoch_format)) == -1) return EXIT_FAILURE;
if ((current_time_calandar_format = localtime(¤t_time_epoch_format)) == NULL) return EXIT_FAILURE;
if (strftime(output_string, 23, "[%d-%m-%Y %H:%M:%S] ", current_time_calandar_format) != 22) return EXIT_FAILURE;
if ((log_file_stream = fopen(log_file_string, "a")) == NULL) return EXIT_FAILURE;
if (printf("%s\n", strcat(output_string, input_string)) < 1) return EXIT_FAILURE;
if (fprintf(log_file_stream, "%s\n", output_string) < 1) return EXIT_FAILURE;
if (fclose(log_file_stream) == EOF) return EXIT_FAILURE;
return EXIT_SUCCESS;
}
int main(int argc, char** argv)
{
/*Initializations.*/
int EXIT_CODE;
/*Print the returned integer from logging_function and exit.*/
printf("%d\n", (EXIT_CODE = logging_function(argv[1], argv[2])));
exit(EXIT_CODE);
}