这是一段测试名为“logf”的函数的代码,该函数接受两个参数并使用它们记录一些信息。在这种情况下,函数的第一个参数是要记录的字符串,第二个参数是保存文件系统中日志文件路径的字符串。第一个字符串与时间戳一起打印到标准输出和日志文件。
#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 logf(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 logf and exit.*/
printf("%d\n", (EXIT_CODE = logf(argv[1], argv[2])));
exit(EXIT_CODE);
}