-
Notifications
You must be signed in to change notification settings - Fork 7
/
mylog.c
executable file
·75 lines (57 loc) · 1.86 KB
/
mylog.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
68
69
70
71
72
73
74
75
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#define LOG_FILE "udat.log"
// a simple log function, works similar to printf
void glog(const char *format, ... ) {
va_list args; // argument list
static FILE *logfile = NULL; // file pointer to the logfile
char *fformat; // the modified format of the string which will be written to the logfile
int length; // length of the format
if(!(format == NULL && logfile == NULL)) {
// open the logfile if not already opened
if(logfile == NULL) {
//logfile = fopen(LOG_FILE, "w");
logfile = fopen(LOG_FILE, "a");
// if that doesn't work exit with an error message
if(logfile == NULL) {
fprintf(stderr, "Cannot open logfile %s\n", LOG_FILE);
exit(EXIT_FAILURE);
}
}
// if NULL is given as format, close the opened file
if(format != NULL) {
// increase length by 2 (for \n\0
length = strlen(format) + 2;
// allocate memory
fformat = malloc(sizeof(char) * length);
// copy the format over
strncpy(fformat, format, length - 2);
// append \n\0
fformat[length - 2] = '\n';
fformat[length - 1] = '\0';
// get the rest of the arguments
va_start(args, format);
// use vfprintf() to
vfprintf(logfile, fformat, args);
// forces the logmessage to be written into the file right now
fflush(logfile);
va_end(args);
// free the allocated memory for the format string
free(fformat);
} else {
// close the logfile
fclose(logfile);
}
}
}
int main(int argc, char*argv[])
{
glog("%d\t%s\n",93,"second");
glog("%d\t%s\n",73,"third");
glog("%s\t%s\n","string-A","string-B");
glog("%s\t%f\n","string-C",3.1415);
printf("done\r\n");
return 0;
}