-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexecution_logger.c
67 lines (53 loc) · 1.75 KB
/
execution_logger.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)
#define MAXBUFFERSIZE 4096
/* This program creates a log file called execution_log.txt which
* leaves a log entry every time the binary is executed, with the
* exact time the program was run.
* */
int main(int argc, char *argv[]) {
struct tm curr_time, *tm_ptr;
char hr_str[3], min_str[3], sec_str[3], day_str[3], mon_str[3], yr_str[5];
tm_ptr = &curr_time;
int fptr = open("execution_log.txt", O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
if (fptr == -1) {
errExit("open log file");
}
long int epoch_time = time(0);
localtime_r(&epoch_time, tm_ptr);
snprintf(hr_str, 3, "%02d", tm_ptr->tm_hour);
snprintf(min_str, 3, "%02d", tm_ptr->tm_min);
snprintf(sec_str, 3, "%02d", tm_ptr->tm_sec);
snprintf(day_str, 3, "%02d", tm_ptr->tm_mday);
snprintf(mon_str, 3, "%02d", tm_ptr->tm_mon + 1);
snprintf(yr_str, 5, "%d", tm_ptr->tm_year + 1900);
char log_entry[100] = "Executed on ";
strcat(log_entry, mon_str);
strcat(log_entry, "/");
strcat(log_entry, day_str);
strcat(log_entry, "/");
strcat(log_entry, yr_str);
strcat(log_entry, " at ");
strcat(log_entry, hr_str);
strcat(log_entry, ":");
strcat(log_entry, min_str);
strcat(log_entry, ":");
strcat(log_entry, sec_str);
strcat(log_entry, "\n");
if (write(fptr, log_entry, strlen(log_entry)) == -1) {
close(fptr);
errExit("write");
}
if (close(fptr) == -1) {
errExit("close");
}
return EXIT_SUCCESS;
}